Created
November 4, 2016 19:53
-
-
Save p4tin/4e4b716aaec152ab19900afe01e51be4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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