How to Use HTTP Basic Authentication in Go

Web
Use SetBasicAuth to send credentials or BasicAuth to validate them in Go HTTP requests and handlers.

Use http.Request.SetBasicAuth to attach credentials or http.BasicAuth to create a handler that validates them.

package main

import (
	"fmt"
	"net/http"
)

func main() {
	// Create a request with Basic Auth credentials
	req, _ := http.NewRequest("GET", "https://example.com/api", nil)
	req.SetBasicAuth("username", "password")

	// Create a handler that requires Basic Auth
	http.HandleFunc("/protected", func(w http.ResponseWriter, r *http.Request) {
		user, pass, ok := r.BasicAuth()
		if !ok || user != "admin" || pass != "secret" {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}
		fmt.Fprintln(w, "Access granted")
	})

	http.ListenAndServe(":8080", nil)
}