regex - How to match subdomain with gorilla mux -
i need build route matches 2 subdomains(prefix.api.example.com , prefix.api.sandbox.example.com) using gorilla mux router. far have regex below router returns 404 on requests. idea why that?
router := mux.newrouter() route := router.host(`prefix.api{_:(^$|^\.sandbox$)}.example.com`)
more code
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)) }
request:
$ curl prefix.api.sandbox.example.com/any -v * trying 127.0.0.1... * connected prefix.api.sandbox.example.com (127.0.0.1) port 80 (#0) > /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 host prefix.api.sandbox.example.com left intact
the ^
, $
metacharacters matching beginning , end of lines should removed, parens can well.
route := router.host(`prefix.api{_:|\.sandbox}.example.com`)`
my hosts file:
○ 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
gives me following:
○ 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
updated:
here regexes generated 2 different .host()
's:
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$
- example tests both regexes can played here @ play.golang