如何在golang中使用regexp获取url模式? [英] How to use regexp get url pattern in golang?

查看:214
本文介绍了如何在golang中使用regexp获取url模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  package main 

导入(
fmt
net / http


func main(){
http.HandleFunc(/模式,解决)
http.ListenAndServe(:8080,零)
}

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


解决方案

http.HandleFunc() 不能用于注册一个模式以匹配正则表达式。简而言之,在 HandleFunc()中指定的模式可以匹配固定的根路径(如 /favico.ico )或根源子树(如 / images / ),较长的模式优先于较短的模式。您可以在 ServeMux 类型。

您可以将您的处理程序注册到一个有根的子树,该树可以是 / code>模式,并且在你的处理程序中,你可以做更多的正则表达式匹配和路由。



例如:

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

$ b $ 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):
数字(w,r)
案例rAbc.MatchString(r.URL.Path):
abc(w,r)
默认值:
w.Write([ ]字节(未知模式))
}
}

func数字(w http.Respo ($ http:// http:// http:// http:// www。 http.Request){
w.Write([] byte(has abc))
}

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


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

解决方案

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.

这篇关于如何在golang中使用regexp获取url模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆