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.
Code
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
errends 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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.