-
-
Save mybigman/9c98dd4b75727081c8c1d19657d367c6 to your computer and use it in GitHub Desktop.
Implement custom http.ResponseWriter in golang
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
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