Basic Authentication in HTTP API requests in Golang

Suraj Narwade's photo
Suraj Narwade
·Feb 12, 2023·

2 min read

Play this article

In Golang, implementing basic authentication in an HTTP API request is relatively straightforward.

Once we construct the request, then we have to call the SetBasicAuth() method and pass username & password

package main

import (

func main() {
    client := &http.Client{}
    req, err := http.NewRequest("GET", "", nil)
    if err != nil {
    req.SetBasicAuth("admin", "password")
    resp, err := client.Do(req)
    if err != nil {
    defer resp.Body.Close()
    bodyText, err := ioutil.ReadAll(resp.Body)
    if err != nil {
    fmt.Printf("%s\n", bodyText)

It is equivalent of,

curl -u username:password


curl -H "Authorization: Basic <base64 encoded username:password >" localhost:8080

Let's understand what SetBasicAuth is the method done behind the scene?


func (r *Request) SetBasicAuth(username, password string) {
    r.Header.Set("Authorization", "Basic "+basicAuth(username, password))

func basicAuth(username, password string) string {
    auth := username + ":" + password
    return base64.StdEncoding.EncodeToString([]byte(auth))

it is adding Auth headers in the request, where username and password and encode to base64

This is a simple example of implementing basic authentication in an HTTP API request in Golang. Keep in mind that in production, it's not recommended to hardcode the credentials in the code. And it's best practice to use HTTPS for added security.

Note: Basic Authentication is not the only way to authenticate a user, and it's not recommended to use it in case of sensitive information or data.

I hope you learnt something new from this blog post. Click here to learn about me and how you can support my work, Thank you!

Did you find this article valuable?

Support Suraj Narwade by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
Share this