Skip to content

Instantly share code, notes, and snippets.

@donatj
Last active Sep 12, 2018
Embed
What would you like to do?
Golang Basic Auth
package utils
import (
"net/http"
)
func BasicAuth(handler http.Handler, username, password string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if u, p, ok := r.BasicAuth(); !ok || !(u == username && p == password) {
w.Header().Set("WWW-Authenticate", "Basic realm=\"ZorkIrc\"")
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
handler.ServeHTTP(w, r)
}
}
@slawosz

This comment has been minimized.

Copy link

@slawosz slawosz commented Oct 19, 2016

Now you can use func (r *Request) BasicAuth() (username, password string, ok bool) from net/http

@donatj

This comment has been minimized.

Copy link
Owner Author

@donatj donatj commented Sep 12, 2018

@slawosz Huh, neat. When was that added?

@donatj

This comment has been minimized.

Copy link
Owner Author

@donatj donatj commented Sep 12, 2018

@slawosz I took your 2¢ into consideration and cleaned this up significantly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment