为了账号安全,请及时绑定邮箱和手机立即绑定

如何将子域与 gorilla mux 匹配

如何将子域与 gorilla mux 匹配

Go
白板的微信 2022-01-17 10:30:47
我需要使用 gorilla mux路由器构建一个匹配两个子域(prefix.api.example.com 和 prefix.api.sandbox.example.com)的路由。到目前为止,我有下面的正则表达式,但路由器在请求时返回 404。知道为什么吗?router := mux.NewRouter()route :=  router.Host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)更多代码package mainimport(    "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 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

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


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$


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


查看完整回答
反对 回复 2022-01-17
  • 1 回答
  • 0 关注
  • 199 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号