Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在golang中使用regexp获取url模式?_Regex_Http_Go_Url Routing - Fatal编程技术网

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

如何在golang中使用regexp获取url模式?,regex,http,go,url-routing,Regex,Http,Go,Url Routing,如何使用正则表达式匹配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

如何使用正则表达式匹配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)
}
无法用于注册模式以匹配正则表达式。简而言之,在
HandleFunc()
处指定的模式可以匹配固定的根路径(如
/favico.ico
)或根子树(如
/images/
),较长的模式优先于较短的模式。您可以在该类型的文档中找到更多详细信息

您可以做的是将处理程序注册到一个根子树中,这可能是
/
模式的所有内容,在处理程序中,您可以进一步进行regexp匹配和路由

例如:

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匹配。而且从头开始实现有点复杂

也许使用一个框架会是一个更好的选择,比如or等等。

我使用包。所以路由器看起来像:

func main() {

    r := mux.NewRouter()

    r.HandleFunc("/{name:pattern}", handle)
    http.ListenAndServe(":8080", r)
}
其中
{name:pattern}
可以是简单的
{slug}
(无模式)或
{id:[0-9]+}
或它们的组合
/{category}/{id:[0-9]+}
。并在handler 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"]
}
运行它并尝试
curlhttp://localhost:8080/whatever/1