Skip to content

Instantly share code, notes, and snippets.

@peterbourgon
Last active November 6, 2016 04:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterbourgon/2d190ddbb8d2cbddb5bceaca80eef20e to your computer and use it in GitHub Desktop.
Save peterbourgon/2d190ddbb8d2cbddb5bceaca80eef20e to your computer and use it in GitHub Desktop.
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
}
}
@phpeter
Copy link

phpeter commented Sep 22, 2016

10: return http.HandleFunc(func(w http.ResponseWriter, r *http.Request) {

Is this a typo? Should it be wrapped in HandlerFunc instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment