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?
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.