| 325 | } |
| 326 | |
| 327 | func (r *Router) allowed(path, reqMethod string) (allow string) { |
| 328 | allowed := make([]string, 0, 9) |
| 329 | |
| 330 | if path == "*" { // server-wide |
| 331 | // empty method is used for internal calls to refresh the cache |
| 332 | if reqMethod == "" { |
| 333 | for method := range r.trees { |
| 334 | if method == http.MethodOptions { |
| 335 | continue |
| 336 | } |
| 337 | // Add request method to list of allowed methods |
| 338 | allowed = append(allowed, method) |
| 339 | } |
| 340 | } else { |
| 341 | return r.globalAllowed |
| 342 | } |
| 343 | } else { // specific path |
| 344 | for method := range r.trees { |
| 345 | // Skip the requested method - we already tried this one |
| 346 | if method == reqMethod || method == http.MethodOptions { |
| 347 | continue |
| 348 | } |
| 349 | |
| 350 | handle, _, _ := r.trees[method].getValue(path) |
| 351 | if handle != nil { |
| 352 | // Add request method to list of allowed methods |
| 353 | allowed = append(allowed, method) |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | if len(allowed) > 0 { |
| 359 | // Add request method to list of allowed methods |
| 360 | allowed = append(allowed, http.MethodOptions) |
| 361 | |
| 362 | // Sort allowed methods. |
| 363 | // sort.Strings(allowed) unfortunately causes unnecessary allocations |
| 364 | // due to allowed being moved to the heap and interface conversion |
| 365 | for i, l := 1, len(allowed); i < l; i++ { |
| 366 | for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- { |
| 367 | allowed[j], allowed[j-1] = allowed[j-1], allowed[j] |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | // return as comma separated list |
| 372 | return strings.Join(allowed, ", ") |
| 373 | } |
| 374 | return |
| 375 | } |
| 376 | |
| 377 | // ServeHTTP makes the router implement the http.Handler interface. |
| 378 | func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { |