Skip to content

Instantly share code, notes, and snippets.

@arriqaaq
Created January 27, 2023 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arriqaaq/c9999d7cdec7f23da0b4484daa947a69 to your computer and use it in GitHub Desktop.
Save arriqaaq/c9999d7cdec7f23da0b4484daa947a69 to your computer and use it in GitHub Desktop.
type Middleware func(http.HandlerFunc) http.HandlerFunc
func LoggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println("Before request")
next.ServeHTTP(w, r)
log.Println("After request")
}
}
func AuthMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user := r.Header.Get("X-User")
if user == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), "user", user)
next.ServeHTTP(w, r.WithContext(ctx))
}
}
func MyHandler(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(string)
fmt.Fprintf(w, "Hello, %s!", user)
}
func main() {
http.HandleFunc("/", LoggingMiddleware(AuthMiddleware(MyHandler)))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment