登录
首页 >  Golang >  Go问答

如何验证 Mux 路由器特定端点的访问权限?

来源:stackoverflow

时间:2024-03-24 13:18:47 226浏览 收藏

**摘要:** 本文探讨了如何验证 Mux 路由器特定端点的访问权限。在遇到 405 响应时,需要通知用户允许的方法。通过修改 `MethodNotAllowedHandler` 处理程序,遍历路由并应用路由匹配功能,可以获取路由允许的方法并将其发送在标头中。本文提供了完整的代码示例,展示了如何实现这一功能。

问题内容

我需要通知用户特定端点允许的方法。如果服务器有 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())
    })

谢谢!


正确答案


您可以修改您的 methodnotallowed 处理程序,如下所示; 它只是遍历路线并应用路线匹配功能。如果路径匹配而方法不匹配,则返回 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)
    })
}

今天关于《如何验证 Mux 路由器特定端点的访问权限?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>