thearyanahmed
thearyanahmed

Reputation: 606

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.

Upvotes: 2

Views: 2264

Answers (2)

Bhupinder Singh Narang
Bhupinder Singh Narang

Reputation: 365

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")
    })
}

Upvotes: 1

Blokje5
Blokje5

Reputation: 5023

Check out some the gorilla/handler repository. It contains middleware handlers (e.g. handlers that are executed before your main handler) including a handler for checking whether a HTTP method is allowed. E.g.:

MethodHandler{
  "GET": myHandler,
}

Any other method will automatically return a 405 Method not allowed response.

Upvotes: 1

Related Questions