Search code examples
gogorillamux

Send custom response in gorilla mux when route method does not match


how can I send a custom response when the route method (HTTP Verb) does not match?

When I hit the following route in a post method

r.handleFunc("/destination", handler).Methods('GET')

I want to receive (let's assume its a JSON response)

{
    status: "ERROR",
    message: "Route method not supported."

}

The idea is that I don't want to have each handler with the route.Method == $METHOD check. Looking for a way where I can define once and apply to each route.


Solution

  • To setup custom return for route methods, you could simply override the handler "MethodNotAllowedHandler" with your own.

    Example:

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    
        "github.com/gorilla/mux"
    )
    
    func main() {
    
        log.Fatal(http.ListenAndServe(":8080", router()))
    }
    
    func router() *mux.Router {
    
        r := mux.NewRouter()
    
        r.HandleFunc("/destination", destination).Methods("GET")
        r.MethodNotAllowedHandler = MethodNotAllowedHandler()
        return r
    }
    
    func destination(w http.ResponseWriter, r *http.Request) {
    
        fmt.Fprintf(w, "destination output")
    }
    
    func MethodNotAllowedHandler() http.Handler {
    
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    
            fmt.Fprintf(w, "Method not allowed")
        })
    }