如何匹配子域与大猩猩多路复用器

时间:2016-06-01 22:02:11

标签: regex go gorilla

我需要使用gorilla mux路由器构建一个匹配两个子域(prefix.api.example.com和prefix.api.sandbox.example.com)的路由。到目前为止,我有下面的正则表达式,但路由器在请求时返回404。知道为什么会这样吗?

router := mux.NewRouter()
route :=  router.Host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)

更多代码

package main

import(
    "github.com/gorilla/mux"
    "net/http"
)

type handler struct{}

func (_ handler)ServeHTTP(w http.ResponseWriter, r *http.Request){
    w.Write([]byte("hello world"))
    w.WriteHeader(200)

}
func main() {
    router := mux.NewRouter().StrictSlash(true)
    route :=  router.Host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)
    route.Handler(handler{})
    http.Handle("/", router)
      panic(http.ListenAndServe(":80", nil))
}

请求:

$ curl prefix.api.sandbox.example.com/any -v
*   Trying 127.0.0.1...
* Connected to prefix.api.sandbox.example.com (127.0.0.1) port 80 (#0)
> GET /some HTTP/1.1
> Host: prefix.api.sandbox.example.com
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 404 Not Found
< Content-Type: text/plain; charset=utf-8
< X-Content-Type-Options: nosniff
< Date: Wed, 01 Jun 2016 22:08:21 GMT
< Content-Length: 19
< 
404 page not found
* Connection #0 to host prefix.api.sandbox.example.com left intact

1 个答案:

答案 0 :(得分:2)

应删除用于匹配行的开头和结尾的^$元字符,也可以删除parens。

route := router.Host(`prefix.api{_:|\.sandbox}.example.com`)`

我的主人档案:

○ grep prefix /etc/hosts
127.0.0.1   prefix.api.example.com
127.0.0.1   prefix.api.sandbox.example.com
127.0.0.1   prefix.api.xsandbox.example.com

给我以下内容:

○ curl prefix.api.example.com:8000
hello world%                                                                                                                                                                                                                                                                    
○ curl prefix.api.sandbox.example.com:8000
hello world%                                                                                                                                                                                                                                                                    
○ curl prefix.api.xsandbox.example.com:8000
404 page not found

<强>更新

以下是两个不同的.Host()生成的正则表达式:

route :=  router.Host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)

regexp:^prefix\.api(?P<v0>(^$|^\.sandbox$))\.example\.com$

route := router.Host(`prefix.api{_:|\.sandbox}.example.com`)

regexp:^prefix\.api(?P<v0>|\.sandbox)\.example\.com$

  • 可以使用两种正则表达式的示例测试 here at play.golang