@@ -156,6 +156,9 @@ type Router struct {
156
156
// Custom OPTIONS handlers take priority over automatic replies.
157
157
HandleOPTIONS bool
158
158
159
+ // Cached value of global (*) allowed methods
160
+ globalAllowed string
161
+
159
162
// Configurable http.Handler which is called when no matching route is
160
163
// found. If it is not set, http.NotFound is used.
161
164
NotFound http.Handler
@@ -245,6 +248,8 @@ func (r *Router) Handle(method, path string, handle Handle) {
245
248
if root == nil {
246
249
root = new (node )
247
250
r .trees [method ] = root
251
+
252
+ r .globalAllowed = r .allowed ("*" , "" )
248
253
}
249
254
250
255
root .addRoute (path , handle )
@@ -317,12 +322,17 @@ func (r *Router) allowed(path, reqMethod string) (allow string) {
317
322
allowed := make ([]string , 0 , 9 )
318
323
319
324
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 )
323
333
}
324
- // Add request method to list of allowed methods
325
- allowed = append ( allowed , method )
334
+ } else {
335
+ return r . globalAllowed
326
336
}
327
337
} else { // specific path
328
338
for method := range r .trees {
@@ -405,7 +415,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
405
415
406
416
if req .Method == http .MethodOptions && r .HandleOPTIONS {
407
417
// 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 {
409
419
w .Header ().Set ("Allow" , allow )
410
420
return
411
421
}
0 commit comments