From f3ff42f93a451d7ffb2ff11cb9485f3f88089c83 Mon Sep 17 00:00:00 2001 From: santsai Date: Fri, 4 Jan 2019 23:08:45 +0800 Subject: [PATCH] getHost() now returns full host & port information (#383) Previously, getHost only returned the host. As it now returns the port as well, any .Host matches on a route will need to be updated to also support matching on the port for cases where the port is non default, eg: 80 for http or 443 for https. --- mux_test.go | 20 +++++++++++++++++++- regexp.go | 10 +++------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/mux_test.go b/mux_test.go index 519aa92..8ad57ac 100644 --- a/mux_test.go +++ b/mux_test.go @@ -104,7 +104,15 @@ func TestHost(t *testing.T) { path: "", shouldMatch: false, }, - // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true}, + { + title: "Host route with port, match with request header", + route: new(Route).Host("aaa.bbb.ccc:1234"), + request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), + vars: map[string]string{}, + host: "aaa.bbb.ccc:1234", + path: "", + shouldMatch: true, + }, { title: "Host route with port, wrong host in request header", route: new(Route).Host("aaa.bbb.ccc:1234"), @@ -114,6 +122,16 @@ func TestHost(t *testing.T) { path: "", shouldMatch: false, }, + { + title: "Host route with pattern, match with request header", + route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc:1{v2:(?:23|4)}"), + request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:123"), + vars: map[string]string{"v1": "bbb", "v2": "23"}, + host: "aaa.bbb.ccc:123", + path: "", + hostTemplate: `aaa.{v1:[a-z]{3}}.ccc:1{v2:(?:23|4)}`, + shouldMatch: true, + }, { title: "Host route with pattern, match", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), diff --git a/regexp.go b/regexp.go index 7c7405d..f252886 100644 --- a/regexp.go +++ b/regexp.go @@ -312,17 +312,13 @@ 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 { if r.URL.IsAbs() { return r.URL.Host } - host := r.Host - // Slice off any port information. - if i := strings.Index(host, ":"); i != -1 { - host = host[:i] - } - return host - + return r.Host } func extractVars(input string, matches []int, names []string, output map[string]string) {