回答

收藏

http.HandleFunc 模式中的通配符

技术问答 技术问答 332 人阅读 | 0 人回复 | 2023-09-12

在 Go(语言)注册处理程序时,有没有办法在模式中指定通配符?
+ ~2 K) [! T' Y4 l2 d例如:' Z% D; A9 a6 ~
    http.HandleFunc("/groups/*/people",peopleInGroupHandler)9 ~1 E+ n6 A. K1 A6 z8 H/ O5 H
其中*任何有效的 URL 字符串。groups ( peopleInGroupHandler) func 匹配和找出其余部分的唯一解决方案?# X$ ^3 v: G8 @) w/ E
                                                                $ N. l% i  k" y
    解决方案:                                                               
  U0 \" r% {# Z7 s9 |& C                                                                http.Handler 和 http.HandleFunc 的模式不是正则的表达式或 glob。没有办法指定通配符。它们记录在这里。7 ]  Q3 A7 z" X0 V: h' F5 S
也就是说,创建自己的处理程序可以使用正则表达式或任何其他类型的模式并不难。这是一种使用正则表达式(已编译但未经测试):
2 u( r2 _9 {& r! w. j; t; s- J
    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)}% ], W5 B  j* V
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则