Last active
June 14, 2024 10:00
-
-
Save nstogner/2d6e122418ad3e21a175974e5c9bb36c to your computer and use it in GitHub Desktop.
Go: HTTP Status Logging Middleware
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
type statusRecorder struct { | |
http.ResponseWriter | |
status int | |
} | |
func (rec *statusRecorder) WriteHeader(code int) { | |
rec.status = code | |
rec.ResponseWriter.WriteHeader(code) | |
} | |
func logware(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
// Initialize the status to 200 in case WriteHeader is not called | |
rec := statusRecorder{w, 200} | |
next.ServeHTTP(&rec, r) | |
log.Printf("response status: %v\n", rec.status) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tks