From ecd8e794b0805eb64bb5a507ebcb1e419df3f031 Mon Sep 17 00:00:00 2001 From: mzajaczkowski Date: Mon, 6 Jan 2020 21:08:36 +0100 Subject: [PATCH] Fix the issue when a wildcard host is not taken into the account when matching vars --- mux_test.go | 10 ++++++++++ regexp.go | 24 +++++++++++++----------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/mux_test.go b/mux_test.go index 2d8d2b3..ee6a301 100644 --- a/mux_test.go +++ b/mux_test.go @@ -146,6 +146,16 @@ func TestHost(t *testing.T) { hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`, shouldMatch: true, }, + { + title: "Host route with pattern, match with wildcard port", + route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), + request: newRequest("GET", "http://aaa.bbb.ccc:8080/111/222/333"), + vars: map[string]string{"v1": "bbb"}, + host: "aaa.bbb.ccc", + path: "", + hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`, + shouldMatch: true, + }, { title: "Host route with pattern, additional capturing group, match", route: new(Route).Host("aaa.{v1:[a-z]{2}(?:b|c)}.ccc"), diff --git a/regexp.go b/regexp.go index b5a15ed..674f31f 100644 --- a/regexp.go +++ b/regexp.go @@ -173,13 +173,7 @@ type routeRegexp struct { // Match matches the regexp against the URL host or path. func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { if r.regexpType == regexpTypeHost { - host := getHost(req) - if r.wildcardHostPort { - // Don't be strict on the port match - if i := strings.Index(host, ":"); i != -1 { - host = host[:i] - } - } + host := getHost(req, r.wildcardHostPort) return r.regexp.MatchString(host) } @@ -287,7 +281,7 @@ type routeRegexpGroup struct { func (v routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { // Store host variables. if v.host != nil { - host := getHost(req) + host := getHost(req, v.host.wildcardHostPort) matches := v.host.regexp.FindStringSubmatchIndex(host) if len(matches) > 0 { extractVars(host, matches, v.host.varsN, m.Vars) @@ -331,11 +325,19 @@ func (v routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { // getHost tries its best to return the request host. // According to section 14.23 of RFC 2616 the Host header // can include the port number if the default value of 80 is not used. -func getHost(r *http.Request) string { +func getHost(r *http.Request, wildcardHostPort bool) string { + var host string if r.URL.IsAbs() { - return r.URL.Host + host = r.URL.Host + } else { + host = r.Host + } + if wildcardHostPort { + if i := strings.Index(host, ":"); i != -1 { + host = host[:i] + } } - return r.Host + return host } func extractVars(input string, matches []int, names []string, output map[string]string) {