How do you handle HTTP authentication with an HTTP client in Go?

To handle HTTP authentication with an HTTP client in Go, you can set the Authorization header in the http.Request object. There are several types of HTTP authentication, including Basic, Digest, and Bearer. Here's an example of how to handle Basic authentication:
HTTP authentication

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
Here's a full running example that demonstrates how to handle HTTP Basic authentication with an HTTP client in Go:

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))
}
This example sends an HTTP GET request to the httpbin.org website that requires HTTP Basic authentication with the username "user" and the password "passwd". The http.NewRequest() function is used to create a new HTTP request, and the Authorization header is set using the req.Header.Add() method. The HTTP request is then sent using the client.Do(req) method, and the response is read and printed to the console using the ioutil.ReadAll() function.

Most Helpful This Week