Custom JSON response for 405 Method Not Allowed

Hi,

As described here, Go 1.22 http.NewServeMux comes with a default 405 Method Not Allowed plain text response but I would like to override this to return a custom JSON response instead. Is it possible without writing a middleware?

Thanks

mux := http.NewServeMux()
mux.HandleFunc("GET /api/info", handler.Info)
1 Like

maybe you can handle all invalid path to a specific handle from there you can customize your message

Not even sure how to do that.

The short answer is: I don’t believe this is possible without a middleware or something along those lines. Here’s the relevant stdlib code:

https://cs.opensource.google/go/go/+/master:src/net/http/server.go;l=2553

It seems they are being strict about enforcing HTTP semantics. In other words: returning JSON means that method IS supported. I think, based on that, you could do something like this:

mux := http.NewServeMux()
// Handle GET requests
mux.HandleFunc("GET /api/info", handler.Info)
// Send friendly JSON to client instead of 405
mux.HandleFunc("/api/info", handler.InfoNotSupported)

Not exactly ideal, but, it’s easy to read and see what this code is doing; and it avoids middleware. Disclaimer: I haven’t used the Go 1.22 routing enhancements yet so I’m not 100% sure how this will behave.