-
-
Save peterbourgon/2d190ddbb8d2cbddb5bceaca80eef20e to your computer and use it in GitHub Desktop.
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
func main() { | |
a := NewAuthorizer() | |
h := WithAuth(a, http.HandlerFunc(Handle)) | |
http.ListenAndServe("/", h) | |
} | |
const TokenContextKey = "MyAppToken" | |
func WithAuth(a Authorizer, next http.Handler) http.Handler { | |
return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) { | |
auth := r.Header.Get("Authorization") | |
if auth == "" { | |
next.ServeHTTP(w, r) // continue without token | |
return | |
} | |
token, err := a.Authorize(auth) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusUnauthorized) | |
return | |
} | |
ctx := context.WithValue(r.Context(), TokenContextKey, token) | |
next.ServeHTTP(w, r.WithContext(ctx)) | |
}) | |
} | |
func Handle(w http.ResponseWriter, r *http.Request) { | |
if token := r.Context().Value(TokenContextKey); token != nil { | |
// User is logged in | |
} else { | |
// User is not logged in | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
10: return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
Is this a typo? Should it be wrapped in HandlerFunc instead?