MCPcopy
hub / github.com/labstack/echo / Add

Method Add

router.go:447–527  ·  view source on GitHub ↗

Add registers a new route for method and path with matching handler.

(route Route)

Source from the content-addressed store, hash-verified

445
446// Add registers a new route for method and path with matching handler.
447func (r *DefaultRouter) Add(route Route) (RouteInfo, error) {
448 if route.Handler == nil {
449 return RouteInfo{}, newAddRouteError(route, errors.New("adding route without handler function"))
450 }
451 method := route.Method
452 path := normalizePathSlash(route.Path)
453
454 h := applyMiddleware(route.Handler, route.Middlewares...)
455 if !r.allowOverwritingRoute {
456 for _, rr := range r.routes {
457 if route.Method == rr.Method && route.Path == rr.Path {
458 return RouteInfo{}, newAddRouteError(route, errors.New("adding duplicate route (same method+path) is not allowed"))
459 }
460 }
461 }
462
463 paramNames := make([]string, 0)
464 originalPath := path
465 wasAdded := false
466 var ri RouteInfo
467 for i, lcpIndex := 0, len(path); i < lcpIndex; i++ {
468 if path[i] == paramLabel {
469 if i > 0 && path[i-1] == '\\' {
470 path = path[:i-1] + path[i:]
471 i--
472 lcpIndex--
473 continue
474 }
475 j := i + 1
476
477 r.insert(staticKind, path[:i], method, routeMethod{RouteInfo: &RouteInfo{Method: method}})
478 for ; i < lcpIndex && path[i] != '/'; i++ {
479 }
480
481 paramNames = append(paramNames, path[j:i])
482 path = path[:j] + path[i:]
483 i, lcpIndex = j, len(path)
484
485 if i == lcpIndex {
486 // path node is last fragment of route path. ie. `/users/:id`
487 ri = route.ToRouteInfo(paramNames)
488 rm := routeMethod{
489 RouteInfo: &RouteInfo{Method: method, Path: originalPath, Parameters: paramNames, Name: route.Name},
490 handler: h,
491 orgRouteInfo: ri,
492 }
493 r.insert(paramKind, path[:i], method, rm)
494 wasAdded = true
495 break
496 } else {
497 r.insert(paramKind, path[:i], method, routeMethod{RouteInfo: &RouteInfo{Method: method}})
498 }
499 } else if path[i] == anyLabel {
500 r.insert(staticKind, path[:i], method, routeMethod{RouteInfo: &RouteInfo{Method: method}})
501 paramNames = append(paramNames, "*")
502 ri = route.ToRouteInfo(paramNames)
503 rm := routeMethod{
504 RouteInfo: &RouteInfo{Method: method, Path: originalPath, Parameters: paramNames, Name: route.Name},

Callers

nothing calls this directly

Calls 6

insertMethod · 0.95
storeRouteInfoMethod · 0.95
newAddRouteErrorFunction · 0.85
normalizePathSlashFunction · 0.85
applyMiddlewareFunction · 0.85
ToRouteInfoMethod · 0.80

Tested by

no test coverage detected