Skip to content

Instantly share code, notes, and snippets.

@AlfredDobradi
Created June 8, 2022 11:05
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 AlfredDobradi/f3de7762636fc299aa2dec4c411fd386 to your computer and use it in GitHub Desktop.
Save AlfredDobradi/f3de7762636fc299aa2dec4c411fd386 to your computer and use it in GitHub Desktop.
Custom ResponseWriter
type MyResponseWriter struct {
http.ResponseWriter
}
func (m MyResponseWriter) Header() Header {
return m.ResponseWriter.Header()
}
func (m MyResponseWriter) Write(d []byte) (int, error) {
return m.ResponseWriter.Write(d)
}
func (m MyResponseWriter) WriteHeader(statusCode int) {
m.ResponseWriter.WriteHeader(statusCode)
}
// And then you can do:
func (g *Gottp) ServeHTTP(res http.ResponseWriter, req *http.Request) {
myWriter := MyResponseWriter(w)
// and then go about your business as usual but using `myWriter instead of w`
}
type MyLoggingResponseWriter struct {
http.ResponseWriter
Status int
Len int
}
func (m *MyLoggingResponseWriter) Header() Header {
return m.ResponseWriter.Header()
}
func (m *MyLoggingResponseWriter) Write(d []byte) (int, error) {
n, err := m.ResponseWriter.Write(d)
m.Len = n
return n, err
}
func (m *MyLoggingResponseWriter) WriteHeader(statusCode int) {
m.Status = statusCode
m.ResponseWriter.WriteHeader(statusCode)
}
// And then you can do:
func (g *Gottp) ServeHTTP(res http.ResponseWriter, req *http.Request) {
myWriter := &MyResponseWriter(w)
// So now after you write a response to the writer, you can log the content-size and the status.
// In this scenario it's not that useful as you could get `n` from `n, err := myWriter.Write()` but I
// usually use this write my logging middleware.
myWriter.Write([]byte("hello"))
log.Printf("The response was %d bytes long and the status was %d (%s)", myWriter.Len, myWriter.Status, http.StatusText(myWriter.Status))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment