Last active
September 12, 2018 19:34
-
-
Save donatj/d5d2055ffd04a3ac192e to your computer and use it in GitHub Desktop.
Golang Basic Auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 Huh, neat. When was that added?
@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
Now you can use
func (r *Request) BasicAuth() (username, password string, ok bool)
fromnet/http