Skip to content

Instantly share code, notes, and snippets.

@genesem
Forked from ciaranarcher/example.go
Created April 2, 2018 08:30
Show Gist options
  • Save genesem/c95cc48fc8e91382e20cdc6dd92b4bb3 to your computer and use it in GitHub Desktop.
Save genesem/c95cc48fc8e91382e20cdc6dd92b4bb3 to your computer and use it in GitHub Desktop.
Wrapping a ResponseWriter to capture the status code
// Create our own MyResponseWriter to wrap a standard http.ResponseWriter
// so we can store the status code.
type MyResponseWriter struct {
status int
http.ResponseWriter
}
func NewMyResponseWriter(res http.ResponseWriter) *MyResponseWriter {
// Default the status code to 200
return &MyResponseWriter{200, res}
}
// Give a way to get the status
func (w MyResponseWriter) Status() int {
return w.status
}
// Satisfy the http.ResponseWriter interface
func (w MyResponseWriter) Header() http.Header {
return w.ResponseWriter.Header()
}
func (w MyResponseWriter) Write(data []byte) (int, error) {
return w.ResponseWriter.Write(data)
}
func (w MyResponseWriter) WriteHeader(statusCode int) {
// Store the status code
w.status = statusCode
// Write the status code onward.
w.ResponseWriter.WriteHeader(statusCode)
}
@genesem
Copy link
Author

genesem commented Apr 2, 2018

used in nanoServ/2 to intercept proxy pass returned status code.

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