drl6054 2015-05-27 06:03 采纳率: 0%
浏览 2344
已采纳

如何在Golang中使用正则表达式获取url模式?

How to use regular expression matching URL, which does decide to use the corresponding function processing

package main

import(
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/pattern", resolve)
  http.ListenAndServe(":8080", nil)
}

func resolve(w http.ResponseWriter, r * http.Request) {
  fmt.Println(r.URL.Host)
}
  • 写回答

3条回答 默认 最新

  • dousendun8411 2015-05-27 06:27
    关注

    http.HandleFunc() can not be used to register a pattern to match a regular expression. In short, the pattern specified at HandleFunc() can match a fixed, rooted path (like /favico.ico) or rooted subtrees (like /images/), longer patterns take precedence over shorter ones. You can find more details at the doc of the ServeMux type.

    What you can do is register your handler to a rooted subtree which may be everything with the / pattern, and inside your handler you can do further regexp matching and routing.

    For example:

    func main() {
        http.HandleFunc("/", route) // Match everything
        http.ListenAndServe(":8080", nil)
    }
    
    var rNum = regexp.MustCompile(`\d`)  // Has digit(s)
    var rAbc = regexp.MustCompile(`abc`) // Contains "abc"
    
    func route(w http.ResponseWriter, r *http.Request) {
        switch {
        case rNum.MatchString(r.URL.Path):
            digits(w, r)
        case rAbc.MatchString(r.URL.Path):
            abc(w, r)
        default:
            w.Write([]byte("Unknown Pattern"))
        }
    }
    
    func digits(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Has digits"))
    }
    
    func abc(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Has abc"))
    }
    

    Or use an external library like Gorilla MUX.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置