Skip to content

Instantly share code, notes, and snippets.

@p4tin
Created November 4, 2016 19:53
Show Gist options
  • Save p4tin/4e4b716aaec152ab19900afe01e51be4 to your computer and use it in GitHub Desktop.
Save p4tin/4e4b716aaec152ab19900afe01e51be4 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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment