Last active
March 19, 2024 21:34
-
-
Save prakashpandey/f8fe3e8f3d446cd3426ac67ac21172f7 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