获取与 http.HandleFunc 匹配的当前模式

问题描述 投票:0回答:2

有没有办法获取触发

http.HandleFunc
的当前路线?也许是这样的?

http.HandleFunc("/foo/", serveFoo)
func serveFoo(rw http.ResponseWriter, req *http.Request) {
    fmt.Println(http.CurrentRoute())
    // Should print "/foo/"
}

我想获取当前路线的原因是因为我发现自己经常写这样的代码。

if req.URL.Path != "/some-route/" {
    http.NotFound(resp, req)
    return
}
// or
key := req.URL.Path[len("/some-other-route/"):]

如果代码能像这样更易于复制粘贴、模块化和干燥,那就太好了。

if req.URL.Path != http.CurrentRoute() {
    http.NotFound(resp, req)
    return
}
// or
key := req.URL.Path[http.CurrentRoute():]

这实际上只是一件小事,所以我不想将整个其他依赖项带入我的项目(Gorilla Mux)。

go
2个回答
1
投票

不可能获取当前匹配的路由,但可以消除场景中的重复代码。编写一个处理程序,在调用另一个处理程序之前检查路径:

func HandleFuncExact(mux *http.ServeMux, pattern string, handler func(http.ResponseWriter, *http.Request) {
    mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
        if req.URL.Path != pattern {
            http.NotFound(w, r)
            return
        }
        handler(w, r)
    })
}

在您的应用程序中,调用包装器而不是 HandlFunc:

HandleFuncExact(http.DefaultServeMux, "/some-route/", serveSomeRoute)

函数

serveSomeRoute
可以假设路径恰好是“/some-route/”。


0
投票

Go 1.23 现在支持这一点。他们添加了

http.Request Pattern
字段 以返回处理程序匹配的模式。

    // Pattern is the [ServeMux] pattern that matched the request.
    // It is empty if the request was not matched against a pattern.
    Pattern string
© www.soinside.com 2019 - 2024. All rights reserved.