Created
June 8, 2022 11:05
-
-
Save AlfredDobradi/f3de7762636fc299aa2dec4c411fd386 to your computer and use it in GitHub Desktop.
Custom ResponseWriter
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 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` | |
} |
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 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