如何在 golang 中使用 regexp get url 模式?

How to use regexp get url pattern in golang?

如何使用正则表达式匹配URL,决定使用哪个函数处理

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)
}

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类型。

你可以做的是将你的处理程序注册到根子树,这可能是所有具有 / 模式的东西,并且在你的处理程序中你可以做进一步的正则表达式匹配和路由。

例如:

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"))
}

或者使用像 Gorilla MUX 这样的外部库。

Golang 没有对 URL 匹配的内置 regex 支持。而且从头开始实施有点复杂。

也许使用框架会是更好的选择,例如beego or martin

我使用 github.com/gorilla/mux 包。所以路由器看起来像:

func main() {

    r := mux.NewRouter()

    r.HandleFunc("/{name:pattern}", handle)
    http.ListenAndServe(":8080", r)
}

其中 {name:pattern} 可以是简单的 {slug}(无模式)或 {id:[0-9]+} 或它们的组合 /{category}/{id:[0-9]+}。并将它们放入处理程序 func:

func handle(w http.ResponseWriter, r *http.Request) {

    params := mux.Vars(r)

    // for /{category}/{id:[0-9]+} pattern
    category := params["category"]
    id := params["id"]
}

运行 它并尝试 curl http://localhost:8080/whatever/1