MCPcopy
hub / github.com/julienschmidt/httprouter / ServeHTTP

Method ServeHTTP

router.go:378–452  ·  view source on GitHub ↗

ServeHTTP makes the router implement the http.Handler interface.

(w http.ResponseWriter, req *http.Request)

Source from the content-addressed store, hash-verified

376
377// ServeHTTP makes the router implement the http.Handler interface.
378func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
379 if r.PanicHandler != nil {
380 defer r.recv(w, req)
381 }
382
383 path := req.URL.Path
384
385 if root := r.trees[req.Method]; root != nil {
386 if handle, ps, tsr := root.getValue(path); handle != nil {
387 handle(w, req, ps)
388 return
389 } else if req.Method != http.MethodConnect && path != "/" {
390 code := 301 // Permanent redirect, request with GET method
391 if req.Method != http.MethodGet {
392 // Temporary redirect, request with same method
393 // As of Go 1.3, Go does not support status code 308.
394 code = 307
395 }
396
397 if tsr && r.RedirectTrailingSlash {
398 if len(path) > 1 && path[len(path)-1] == '/' {
399 req.URL.Path = path[:len(path)-1]
400 } else {
401 req.URL.Path = path + "/"
402 }
403 http.Redirect(w, req, req.URL.String(), code)
404 return
405 }
406
407 // Try to fix the request path
408 if r.RedirectFixedPath {
409 fixedPath, found := root.findCaseInsensitivePath(
410 CleanPath(path),
411 r.RedirectTrailingSlash,
412 )
413 if found {
414 req.URL.Path = string(fixedPath)
415 http.Redirect(w, req, req.URL.String(), code)
416 return
417 }
418 }
419 }
420 }
421
422 if req.Method == http.MethodOptions && r.HandleOPTIONS {
423 // Handle OPTIONS requests
424 if allow := r.allowed(path, http.MethodOptions); allow != "" {
425 w.Header().Set("Allow", allow)
426 if r.GlobalOPTIONS != nil {
427 r.GlobalOPTIONS.ServeHTTP(w, req)
428 }
429 return
430 }
431 } else if r.HandleMethodNotAllowed { // Handle 405
432 if allow := r.allowed(path, req.Method); allow != "" {
433 w.Header().Set("Allow", allow)
434 if r.MethodNotAllowed != nil {
435 r.MethodNotAllowed.ServeHTTP(w, req)

Callers 2

HandlerMethod · 0.45
ServeFilesMethod · 0.45

Calls 6

recvMethod · 0.95
allowedMethod · 0.95
CleanPathFunction · 0.85
getValueMethod · 0.80
HeaderMethod · 0.80

Tested by

no test coverage detected