Here is an example of using basic authentication with the Go HTTP client:
package main
import (
"bytes"
"encoding/base64"
"fmt"
"net/http"
)
func main() {
// Set up basic auth credentials
username := "username"
password := "password"
auth := username + ":" + password
basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
// Create a new request
req, err := http.NewRequest("GET", "https://example.com/api/resource", bytes.NewBuffer(nil))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Add basic auth header to the request
req.Header.Set("Authorization", basicAuth)
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
// Read the response body
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
// Print the response body
fmt.Println(string(body))
}
This code sets up the basic auth credentials for the desired user and password, creates a new GET request with an empty body, adds the basic auth header to the request, sends the request using the HTTP client, reads the response body, and prints it to the console.