| 355 | } |
| 356 | |
| 357 | func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 358 | wrappedWriter := &responseWriterWrapper{ResponseWriter: w} |
| 359 | |
| 360 | ctx := &Ctx{ |
| 361 | Server: server, |
| 362 | Method: r.Method, |
| 363 | BaseURI: r.URL.Path, |
| 364 | Request: r, |
| 365 | Response: wrappedWriter, |
| 366 | params: make(map[string]string), |
| 367 | } |
| 368 | |
| 369 | handlers, params, found := server.router.Search(r.Method, r.URL.Path) |
| 370 | |
| 371 | if !found && r.Method == MethodOptions { |
| 372 | // CORS preflight: find handlers registered under any method for this path. |
| 373 | handlers, params, found = server.router.SearchAnyMethod(r.URL.Path) |
| 374 | } |
| 375 | |
| 376 | if !found { |
| 377 | // Check if the path exists under a different method (→ 405). |
| 378 | if _, _, exists := server.router.SearchAnyMethod(r.URL.Path); exists { |
| 379 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) |
| 380 | return |
| 381 | } |
| 382 | http.NotFound(w, r) |
| 383 | return |
| 384 | } |
| 385 | |
| 386 | ctx.params = params |
| 387 | server.limitMaxRequestBodySize(w, r) |
| 388 | |
| 389 | for _, handler := range handlers { |
| 390 | if err := handler(ctx); err != nil { |
| 391 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 392 | return |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | func (server *Server) limitMaxRequestBodySize(w http.ResponseWriter, r *http.Request) { |
| 398 | r.Body = http.MaxBytesReader(w, r.Body, server.config.BodyLimit) |