Skip to content

Instantly share code, notes, and snippets.

@vardius

vardius/main.go

Last active Jun 11, 2020
Embed
What would you like to do?
Basic HTTP authentication with Go
package main
import (
"crypto/subtle"
"fmt"
"log"
"net/http"
)
var (
requiredUser = []byte("gordon")
requiredPassword = []byte("secret!")
)
func BasicAuth(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Get the Basic Authentication credentials
user, password, hasAuth := r.BasicAuth()
if !hasAuth || subtle.ConstantTimeCompare(requiredUser, []byte(user)) != 1 || subtle.ConstantTimeCompare(requiredPassword, []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func index(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "Not protected!\n")
}
func protected(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, "Protected!\n")
}
func main() {
http.HandleFunc("/", index)
http.Handle("/protected", BasicAuth(http.HandlerFunc(protected)))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.