regex - 如何将子域与 gorilla mux 匹配

标签 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

最佳答案

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

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

关于regex - 如何将子域与 gorilla mux 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37579525/

相关文章:

regex - 根据输出用正则表达式获取值

javascript - PHP/JS Ajax _POST 数组未发布

reactjs - 如何设置服务 reactjs 应用程序的路由?

regex - 正则表达式的 BNF 是什么(为了编写完整或部分解析器)

web-applications - `alice` 未调用中间件

go - 如何处理可以无阻塞增长的队列

struct - Go中的结构体大小

Golang - 如何获得 mux 的授权?

json - Go lang( postman )中的请求正文为空

regex - 如何巧妙地将 "x"和 "[x]"与正则表达式匹配而不重复?