Created
January 27, 2023 09:51
-
-
Save arriqaaq/c9999d7cdec7f23da0b4484daa947a69 to your computer and use it in GitHub Desktop.
This file contains 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
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