duanlie1298 2011-07-03 18:00
浏览 424
已采纳

http.HandleFunc模式中的通配符

When registering handlers in Go (language) is there any way to specify wildcards in the pattern?

For example:

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

Where the * could be any valid URL string. Or is the only solution to match /groups and figure the rest out from within the handler (peopleInGroupHandler) func?

  • 写回答

6条回答 默认 最新

  • douchun6108 2011-07-03 20:34
    关注

    The patterns for http.Handler and http.HandleFunc aren't regular expressions or globs. There isn't a way to specify wildcards. They're documented here.

    That said, it's not too hard to create your own handler that can use regular expressions or any other kind of pattern you want. Here's one that uses regular expressions (compiled, but not tested):

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?