Home | About | Apps | Rss

Basic Auth

24 Mar 2021

Code snippet to perform basic auth using go. Every incoming request is required to pass the the username/password combination in the headers and you are expected to validate and return a www-authenticate header response in case of auth failure.

hFunc := func(w http.ResponseWriter, r *http.Request) {
    user, pass, ok := r.BasicAuth()
    if !ok {
        fmt.Println("Error parsing basic auth")
        w.Header().Set("WWW-Authenticate", `Basic realm="mydomain"`)
    // ... do your thing
return http.handlerFunc(hFunc)

More posts