Skip to content

Commit aff381b

Browse files
committed
router: cache allowed methods for *
1 parent bcdc802 commit aff381b

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

router.go

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,9 @@ type Router struct {
156156
// Custom OPTIONS handlers take priority over automatic replies.
157157
HandleOPTIONS bool
158158

159+
// Cached value of global (*) allowed methods
160+
globalAllowed string
161+
159162
// Configurable http.Handler which is called when no matching route is
160163
// found. If it is not set, http.NotFound is used.
161164
NotFound http.Handler
@@ -245,6 +248,8 @@ func (r *Router) Handle(method, path string, handle Handle) {
245248
if root == nil {
246249
root = new(node)
247250
r.trees[method] = root
251+
252+
r.globalAllowed = r.allowed("*", "")
248253
}
249254

250255
root.addRoute(path, handle)
@@ -317,12 +322,17 @@ func (r *Router) allowed(path, reqMethod string) (allow string) {
317322
allowed := make([]string, 0, 9)
318323

319324
if path == "*" { // server-wide
320-
for method := range r.trees {
321-
if method == http.MethodOptions {
322-
continue
325+
// empty method is used for internal calls to refresh the cache
326+
if reqMethod == "" {
327+
for method := range r.trees {
328+
if method == http.MethodOptions {
329+
continue
330+
}
331+
// Add request method to list of allowed methods
332+
allowed = append(allowed, method)
323333
}
324-
// Add request method to list of allowed methods
325-
allowed = append(allowed, method)
334+
} else {
335+
return r.globalAllowed
326336
}
327337
} else { // specific path
328338
for method := range r.trees {
@@ -405,7 +415,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
405415

406416
if req.Method == http.MethodOptions && r.HandleOPTIONS {
407417
// Handle OPTIONS requests
408-
if allow := r.allowed(path, req.Method); len(allow) > 0 {
418+
if allow := r.allowed(path, http.MethodOptions); len(allow) > 0 {
409419
w.Header().Set("Allow", allow)
410420
return
411421
}

0 commit comments

Comments
 (0)