Skip to content

Instantly share code, notes, and snippets.

@donatj
Last active September 12, 2018 19:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save donatj/d5d2055ffd04a3ac192e to your computer and use it in GitHub Desktop.
Save donatj/d5d2055ffd04a3ac192e to your computer and use it in GitHub Desktop.
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
Copy link

slawosz commented Oct 19, 2016

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

@donatj
Copy link
Author

donatj commented Sep 12, 2018

@slawosz Huh, neat. When was that added?

@donatj
Copy link
Author

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