Skip to content

Instantly share code, notes, and snippets.

@sivsivsree
Created July 20, 2022 08:47
Show Gist options
  • Save sivsivsree/fcd434c68f53107182545e56add47327 to your computer and use it in GitHub Desktop.
Save sivsivsree/fcd434c68f53107182545e56add47327 to your computer and use it in GitHub Desktop.
func main() {
mux := http.NewServeMux()
finalHandler := http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
// the context value is retrieved from the request
user := request.Context().Value("user").(string)
writer.Write([]byte(user))
})
mux.Handle("/", middleware(finalHandler))
err := http.ListenAndServe(":3000", mux)
log.Fatal(err)
}
// The middleware function will validate all the requests
// and propagate with context value, you can use the context with
// value to pass tracing id, log ref, user id, across the services.
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token") // this can be JWT, some other token
user := "anonymous"
if token != "" {
// if token is not empty you can parse the token
// parseTokenGetUser()
user = "validated user"
}
// user value is passed along the request context
ctx := context.WithValue(r.Context(), "user", user)
// request.WithContext returns Request with context value included.
next.ServeHTTP(w, r.WithContext(ctx))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment