Skip to content

Commit ed099d4

Browse files
cognusionelithrar
authored andcommitted
host:port matching does not require a :port to be specified.
In lieu of checking the template pattern on every Match request, a bool is added to the routeRegexp, and set if the routeRegexp is a host AND there is no ":" in the template. I dislike extending the type, but I'd dislike doing a string match on every single Match, even more.
1 parent c5c6c98 commit ed099d4

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

regexp.go

+27-10
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,13 @@ func newRouteRegexp(tpl string, typ regexpType, options routeRegexpOptions) (*ro
113113
if typ != regexpTypePrefix {
114114
pattern.WriteByte('$')
115115
}
116+
117+
var wildcardHostPort bool
118+
if typ == regexpTypeHost {
119+
if !strings.Contains(pattern.String(), ":") {
120+
wildcardHostPort = true
121+
}
122+
}
116123
reverse.WriteString(raw)
117124
if endSlash {
118125
reverse.WriteByte('/')
@@ -131,13 +138,14 @@ func newRouteRegexp(tpl string, typ regexpType, options routeRegexpOptions) (*ro
131138

132139
// Done!
133140
return &routeRegexp{
134-
template: template,
135-
regexpType: typ,
136-
options: options,
137-
regexp: reg,
138-
reverse: reverse.String(),
139-
varsN: varsN,
140-
varsR: varsR,
141+
template: template,
142+
regexpType: typ,
143+
options: options,
144+
regexp: reg,
145+
reverse: reverse.String(),
146+
varsN: varsN,
147+
varsR: varsR,
148+
wildcardHostPort: wildcardHostPort,
141149
}, nil
142150
}
143151

@@ -158,11 +166,22 @@ type routeRegexp struct {
158166
varsN []string
159167
// Variable regexps (validators).
160168
varsR []*regexp.Regexp
169+
// Wildcard host-port (no strict port match in hostname)
170+
wildcardHostPort bool
161171
}
162172

163173
// Match matches the regexp against the URL host or path.
164174
func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
165-
if r.regexpType != regexpTypeHost {
175+
if r.regexpType == regexpTypeHost {
176+
host := getHost(req)
177+
if r.wildcardHostPort {
178+
// Don't be strict on the port match
179+
if i := strings.Index(host, ":"); i != -1 {
180+
host = host[:i]
181+
}
182+
}
183+
return r.regexp.MatchString(host)
184+
} else {
166185
if r.regexpType == regexpTypeQuery {
167186
return r.matchQueryString(req)
168187
}
@@ -172,8 +191,6 @@ func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
172191
}
173192
return r.regexp.MatchString(path)
174193
}
175-
176-
return r.regexp.MatchString(getHost(req))
177194
}
178195

179196
// url builds a URL part using the given values.

0 commit comments

Comments
 (0)