[Go] Send an HTTP request with Basic authentication

Created on November 28, 2026

You can use Request.SetBasicAuth() from the net/http package to send a request to a URL protected by HTTP Basic authentication. This example creates a *http.Request, passes the username dummy_user_name and password dummy_password to SetBasicAuth(), and sends the GET request.

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    request, err := http.NewRequest("GET", "https://example.com/basic_auth/", nil)
    if err != nil {
        fmt.Println(err.Error())
    }

    request.SetBasicAuth("dummy_user_name", "dummy_password")

    client := &http.Client{}

    response, err := client.Do(request)
    if err != nil {
        fmt.Println(err.Error())
    }
    defer response.Body.Close()

    responseBody, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println(err.Error())
    }

    fmt.Print(string(responseBody))
}
Go