How do you handle HTTP authentication with an HTTP client in Go?
Example
client := &http.Client{
Transport: &http.Transport{},
}
req, err := http.NewRequest("GET", "https://www.example.com", nil)
if err != nil {
// handle error
}
username := "myusername"
password := "mypassword"
req.SetBasicAuth(username, password)
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
// read response
In this example, an http.Client is created with a http.Transport. An http.Request is then created with the http.NewRequest() function.
The SetBasicAuth() method is then called on the http.Request object to set the Authorization header with the specified username and password. The Do() method of the http.Client is then called with the request, which sends the request with the 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 of the form username:password. This is not secure over an unencrypted connection, so you should use HTTPS to encrypt the connection between the client and the server. You can also use more secure forms of authentication, such as Digest or Bearer authentication. To do so, you would need to set the appropriate headers and parameters for the chosen authentication scheme.
Example
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
)
func main() {
// Create a new HTTP client
client := &http.Client{}
// Create a new HTTP request
req, err := http.NewRequest("GET", "http://httpbin.org/basic-auth/user/passwd", nil)
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Set the HTTP Basic authentication header
username := "user"
password := "passwd"
auth := username + ":" + password
base64Auth := base64.StdEncoding.EncodeToString([]byte(auth))
req.Header.Add("Authorization", "Basic "+base64Auth)
// Send the HTTP request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Check the HTTP status code
if resp.StatusCode != http.StatusOK {
fmt.Println("HTTP Error:", resp.Status)
return
}
// Read the HTTP response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response:", err)
return
}
// Print the HTTP response body
fmt.Println("Response Body:", string(body))
}