Handle basic authentication
To handle HTTP authentication using an HTTP client in Go, you can set the Authorization header in http. Request object. There are many types of HTTP authentication, including basic authentication, digest authentication, and holder authentication.
It is created using
Here is an example of how to handle basic authentication:
client := &{ Transport: &{}, } req, err := ("GET", "", nil) if err != nil { // handle error } username := "myusername" password := "mypassword" (username, password) resp, err := (req) if err != nil { // handle error } defer () // read response
In this example, it is created using. A http. Then use the() function.
Then call the SetBasicAuth() method on http. Request object, set the Authorization header with the specified username and password. The Do() method of http. The client is then called with a request, which sends the request with authentication information to the server. The response is stored in the resp variable for further processing.
Note that the SetBasicAuth() method sets the Authorization header to a base64 encoded string formatted to username: password. This is not secure on unencrypted connections, so HTTPS should be used to encrypt the connection between the client and the server. You can also use more secure forms of authentication, such as digest authentication or holder authentication. To do this, you need to set the appropriate headers and parameters for the selected authentication scheme.
Use the() function
Here is a complete running example that demonstrates how to handle HTTP basic authentication using an HTTP client in Go:
package main import ( "fmt" "net/http" "net/url" "strings" ) func main() { // Create an instance client := &{} // Set the get method and url req, err := ("GET", "/basic-auth/user/passwd", nil) if err != nil { ("Error creating request:", err) return } // Set username and password header username := "user" password := "passwd" auth := username + ":" + password base64Auth := ([]byte(auth)) ("Authorization", "Basic "+base64Auth) // Send a request resp, err := (req) if err != nil { ("Error sending request:", err) return } defer () // Check the http status code if != { ("HTTP Error:", ) return } // Read body body, err := () if err != nil { ("Error reading response:", err) return } // Print body ("Response Body:", string(body)) }
This example sends an HTTP GET request to a website that requires HTTP basic authentication using the username "user" and password "passwd". The () function is used to create a new HTTP request and set the Authorization header using the () method. Then use the Do(req) method to send the HTTP request and use the() function to read the response and print it to the console.
The above is the detailed content of the tutorial example of how Go language handles HTTP authentication. For more information about Go HTTP authentication, please follow my other related articles!