Skip to content

Instantly share code, notes, and snippets.

@prakashpandey
Last active March 19, 2024 21:34
Show Gist options
  • Save prakashpandey/f8fe3e8f3d446cd3426ac67ac21172f7 to your computer and use it in GitHub Desktop.
Save prakashpandey/f8fe3e8f3d446cd3426ac67ac21172f7 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