如何将子域与大猩猩 mux 匹配

How to match subdomain with gorilla mux

我需要使用大猩猩 mux 路由器构建匹配两个子域(prefix.api.example.com 和 prefix.api.sandbox.example.com)的路由。到目前为止,我有下面的正则表达式,但路由器 returns 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

应该删除用于匹配行首和行尾的 ^$ 元字符,括号也可以。

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

正则表达式:^prefix\.api(?P<v0>(^$|^\.sandbox$))\.example\.com$

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

正则表达式:^prefix\.api(?P<v0>|\.sandbox)\.example\.com$

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