【问题标题】:Send custom response in gorilla mux when route method does not match当路由方法不匹配时,在 gorilla mux 中发送自定义响应
【发布时间】:2020-06-16 10:37:03
【问题描述】:

当路由方法(HTTP 动词)不匹配时如何发送自定义响应?

当我在 post 方法中点击以下路线时

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

我想接收(假设它是 JSON 响应)

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

}

我的想法是我不想让每个处理程序都带有 route.Method == $METHOD 检查。寻找一种我可以定义一次并应用于每条路线的方法。

【问题讨论】:

    标签: go gorilla mux


    【解决方案1】:

    要为路由方法设置自定义返回,您可以简单地用自己的处理程序“MethodNotAllowedHandler”覆盖。

    例子:

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

    【讨论】:

      【解决方案2】:

      查看一些 gorilla/handler 存储库。它包含中间件处理程序(例如,在主处理程序之前执行的处理程序),包括handler for checking whether a HTTP method is allowed。例如:

      MethodHandler{
        "GET": myHandler,
      }
      

      任何其他方法都会自动返回405 Method not allowed 响应。

      【讨论】:

        猜你喜欢
        • 2021-06-05
        • 2018-03-13
        • 2016-04-26
        • 2014-11-30
        • 2014-03-07
        • 2015-06-17
        • 1970-01-01
        • 2014-09-08
        • 2016-04-07
        相关资源
        最近更新 更多