Skip to content

Instantly share code, notes, and snippets.

@nstogner
Last active June 14, 2024 10:00
Show Gist options
  • Save nstogner/2d6e122418ad3e21a175974e5c9bb36c to your computer and use it in GitHub Desktop.
Save nstogner/2d6e122418ad3e21a175974e5c9bb36c to your computer and use it in GitHub Desktop.
Go: HTTP Status Logging Middleware
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)
})
}
@MarcusAdriano
Copy link

Tks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment