How to use regexp get url pattern in golang?

huangapple go评论89阅读模式
英文:

How to use regexp get url pattern in golang?

问题

如何使用正则表达式匹配URL,并决定使用相应的函数进行处理

package main

import (
    "fmt"
    "net/http"
    "regexp"
)

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

func resolve(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.URL.Host)

    // 使用正则表达式匹配URL
    matched, _ := regexp.MatchString(`^/pattern`, r.URL.Path)
    if matched {
        // 执行相应的处理函数
        // ...
    }
}
英文:

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

答案1

得分: 12

http.HandleFunc() 不能用于注册匹配正则表达式的模式。简而言之,HandleFunc() 中指定的模式可以匹配固定的根路径(如 /favico.ico)或根子树(如 /images/),较长的模式优先于较短的模式。你可以在 ServeMux 类型的文档中找到更多详细信息。

你可以将处理程序注册到一个根子树,该子树可以匹配 / 模式的所有内容,并在处理程序内部进行进一步的正则表达式匹配和路由。

例如:

func main() {
    http.HandleFunc("/", route) // 匹配所有内容
    http.ListenAndServe(":8080", nil)
}

var rNum = regexp.MustCompile(`\d`)  // 包含数字
var rAbc = regexp.MustCompile(`abc`) // 包含 "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("未知模式"))
    }
}

func digits(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("包含数字"))
}

func abc(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("包含 abc"))
}

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

英文:

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

得分: 4

我使用 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 handle(w http.ResponseWriter, r *http.Request) {
    
    params := mux.Vars(r)

    // 对于 /{category}/{id:[0-9]+} 模式
    category := params["category"]
    id := params["id"]
}

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

英文:

I use github.com/gorilla/mux package. So router looks like:

func main() {

    r := mux.NewRouter()

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

where {name:pattern} could be simply {slug} (without pattern) or {id:[0-9]+} or combination of them /{category}/{id:[0-9]+}. And get them in 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"]
}

run it and try curl http://localhost:8080/whatever/1

答案3

得分: 1

Golang没有内置的正则表达式(regex)支持来进行URL匹配。而且从头开始实现它有些复杂。

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

英文:

Golang doesn't have built-in regex support for URL matching. And it's somewhat complicated to implement from scratch.

Maybe using a framework would be a better choice, such as beego or martin, etc.

huangapple
  • 本文由 发表于 2015年5月27日 14:03:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/30474313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定