-
-
Save avary/805d5db4af7b52b9ddb00a5dffcd7809 to your computer and use it in GitHub Desktop.
Implement custom http.ResponseWriter in golang
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
package main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
type CustomResponseWriter struct { | |
body []byte | |
statusCode int | |
header http.Header | |
} | |
func NewCustomResponseWriter() *CustomResponseWriter { | |
return &CustomResponseWriter{ | |
header: http.Header{}, | |
} | |
} | |
func (w *CustomResponseWriter) Header() http.Header { | |
return w.header | |
} | |
func (w *CustomResponseWriter) Write(b []byte) (int, error) { | |
w.body = b | |
// implement it as per your requirement | |
return 0, nil | |
} | |
func (w *CustomResponseWriter) WriteHeader(statusCode int) { | |
w.statusCode = statusCode | |
} | |
var okFn = func(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(http.StatusOK) | |
} | |
func main() { | |
r := &http.Request{ | |
Method: http.MethodPost, | |
} | |
w := NewCustomResponseWriter() | |
okFn(w, r) | |
fmt.Println(w.statusCode) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment