Skip to content

Instantly share code, notes, and snippets.

@avary
Forked from prakashpandey/CustomResponseWriter.go
Created January 9, 2024 05:51
Show Gist options
  • Save avary/805d5db4af7b52b9ddb00a5dffcd7809 to your computer and use it in GitHub Desktop.
Save avary/805d5db4af7b52b9ddb00a5dffcd7809 to your computer and use it in GitHub Desktop.
Implement custom http.ResponseWriter in golang
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