I am trying to return JSON responses for Not Found and Method Not Allowed responses when using the net/http ServeMux. I implemented this as a middleware and would appreciate any feedback on what could be done better. Also, please let me know if there is a simpler way. Thanks!
type ResponseWriterInterceptor struct {
w http.ResponseWriter
status int
}
func (i *ResponseWriterInterceptor) Header() http.Header {
return i.w.Header()
}
func (i *ResponseWriterInterceptor) Write(b []byte) (int, error) {
if string(b) == "Method Not Allowed\n" || string(b) == "404 page not found\n" {
return 0, nil
}
return i.w.Write(b)
}
func (i *ResponseWriterInterceptor) WriteHeader(statusCode int) {
i.status = statusCode
}
func (app *application) JSONError(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
i := &ResponseWriterInterceptor{w: w}
next.ServeHTTP(i, r)
switch i.status {
case http.StatusNotFound:
app.notFoundResponse(w, r)
case http.StatusMethodNotAllowed:
app.methodNotAllowedResponse(w, r)
}
})
}