小编典典

http.HandleFunc 模式中的通配符

go

在 Go(语言)中注册处理程序时,有没有办法在模式中指定通配符?

例如:

http.HandleFunc("/groups/*/people", peopleInGroupHandler)

其中*可以是任何有效的 URL 字符串。或者是/groups从处理程序 ( peopleInGroupHandler) func 中匹配和找出其余部分的唯一解决方案?


阅读 214

收藏
2021-12-14

共1个答案

小编典典

http.Handler 和 http.HandleFunc 的模式不是正则表达式或 glob。没有办法指定通配符。它们记录在此处

也就是说,创建自己的可以使用正则表达式或任何其他类型的模式的处理程序并不太难。这是使用正则表达式的一个(已编译,但未经测试):

type route struct {
    pattern *regexp.Regexp
    handler http.Handler
}

type RegexpHandler struct {
    routes []*route
}

func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
    h.routes = append(h.routes, &route{pattern, handler})
}

func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
    h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}

func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    for _, route := range h.routes {
        if route.pattern.MatchString(r.URL.Path) {
            route.handler.ServeHTTP(w, r)
            return
        }
    }
    // no pattern matched; send 404 response
    http.NotFound(w, r)
}
2021-12-14