Created
January 13, 2016 22:22
-
-
Save JSila/202544d88436c40bf181 to your computer and use it in GitHub Desktop.
Basic Auth middleware with example of use
This file contains 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 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