Skip to content

Instantly share code, notes, and snippets.

@JSila
Created January 13, 2016 22:22
Show Gist options
  • Save JSila/202544d88436c40bf181 to your computer and use it in GitHub Desktop.
Save JSila/202544d88436c40bf181 to your computer and use it in GitHub Desktop.
Basic Auth middleware with example of use
package main
import (
"fmt"
"net/http"
)
func BasicAuth(username string, password string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth == "" {
w.Header().Set("WWW-Authenticate", "Basic Realm=\"Ma App\"")
http.Error(w, http.StatusText(401), 401)
return
}
authUser, authPass, ok := r.BasicAuth()
if !ok || authUser != username || authPass != password {
http.Error(w, http.StatusText(403), 403)
return
}
next.ServeHTTP(w, r)
})
}
}
func ShowIndex(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to secured page")
}
func main() {
basic := BasicAuth("jernej", "sila")
http.Handle("/", basic(http.HandlerFunc(ShowIndex)))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment