Basic Auth Header With SetBasicAuth

SetBasicAuth writes the standard Authorization header for you: base64 of user:password that decodes back with a single colon separator.

GoAuth Jwt

Code

snippet
package main

import (
	"encoding/base64"
	"fmt"
	"net/http"
	"strings"
)

func main() {
	req, err := http.NewRequest(http.MethodGet, "https://api.example.test/v1/orders", nil)
	if err != nil {
		panic(err)
	}

	// SetBasicAuth writes the standard Authorization header for you
	req.SetBasicAuth("svc-orders", "s3cret-token")
	header := req.Header.Get("Authorization")
	scheme, credentials, _ := strings.Cut(header, " ")
	fmt.Println("scheme:", scheme)
	fmt.Println("credentials:", credentials)

	// the credentials are base64 of user:password with a single colon
	decoded, err := base64.StdEncoding.DecodeString(credentials)
	if err != nil {
		panic(err)
	}
	user, pass, ok := strings.Cut(string(decoded), ":")
	fmt.Println("user:", user, "| password found:", ok, "| pass length:", len(pass))
}

How the snippet works

Every runnable line is contained in the function main.

err is tested at 2 places, and a non-nil one aborts the run with panic(err).

Caveats

  • No install step: the snippet lives entirely inside the standard library.
  • The snippet does not return errors — any non-nil err ends the run immediately.

Applying it

The main signature, verbatim, is func main()

The run emits 3 labeled sections — scheme:, credentials:, user: — one per step.

Statements that matter most here

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
What does Basic Auth Header With SetBasicAuth print when run?
Execute the whole file; each printed line is prefixed with a label like `scheme:`, `credentials:`, `user:`.