【问题标题】:How to check Mux router on allowed methods for specific endpoint?如何在特定端点的允许方法上检查 Mux 路由器?
【发布时间】:2021-12-23 15:07:19
【问题描述】:

我需要通知用户特定端点的允许方法。如果服务器有 405 响应(我使用的是 gorilla/mux),则会显示此信息。

我尝试使用 mux 的自定义处理程序来处理 405,但在 Request 对象和 ResponseWriter 中找不到任何信息。

阅读文档和 SO 后,我找不到任何内容。我可以知道是否有人以前做过同样的事情吗?

代码如下。我显然只允许GET

router.HandleFunc("/users/{id}",).Methods(http.MethodGet)

在我的 405 处理程序中,响应标头显然是空的。没有关于此端点允许的方法的信息。

func MethodNotAllowedHandler() http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        logrus.Debugln("Header Writer: ", w.Header())
    })

谢谢!

【问题讨论】:

    标签: go gorilla mux


    【解决方案1】:

    您可以修改您的 MethodNotAllowed 处理程序,如下所示; 它只是简单地遍历路线并应用 routematch 功能。如果路径匹配而方法不匹配,则返回 mux.ErrMethodMismatch 错误。然后您可以获取路由的允许方法并将其发送到标头中

    func notAllowedHandler(x *mux.Router) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    
            //next.ServeHTTP(w, r)
            x.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
                var routeMatch mux.RouteMatch
                if route.Match(r, &routeMatch) || routeMatch.MatchErr == mux.ErrMethodMismatch {
                    m, _ := route.GetMethods()
                    w.Header().Set("Access-Control-Allow-Methods", strings.Join(m, ", "))
                }
                return nil
            })
            http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
        })
    }
    

    编辑:我忘了提。您需要将路由器参数传递给您的自定义方法不允许的处理程序;

    您可以在下面找到完整的示例;

    func main() {
        r := mux.NewRouter()
        r.HandleFunc("/test", func(rw http.ResponseWriter, r *http.Request) {}).Methods(http.MethodPost)
        r.HandleFunc("/test2", func(rw http.ResponseWriter, r *http.Request) {}).Methods(http.MethodPut)
    
        r.MethodNotAllowedHandler = notAllowedHandler(r)
    
        http.ListenAndServe(":8089", r)
    }
    
    func notAllowedHandler(x *mux.Router) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    
            
            x.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
                var routeMatch mux.RouteMatch
                if route.Match(r, &routeMatch) || routeMatch.MatchErr == mux.ErrMethodMismatch {
                    m, _ := route.GetMethods()
                    w.Header().Set("Access-Control-Allow-Methods", strings.Join(m, ", "))
                }
                return nil
            })
            http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 2018-03-28
      • 2016-09-25
      相关资源
      最近更新 更多