Mount attaches another http.Handler or chi Router as a subrouter along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Mount. See _examples/. Note that Mount() simply sets a wildcard along the `pattern` that will contin
(pattern string, handler http.Handler)
| 287 | // routing at the `handler`, which in most cases is another chi.Router. As a result, |
| 288 | // if you define two Mount() routes on the exact same pattern the mount will panic. |
| 289 | func (mx *Mux) Mount(pattern string, handler http.Handler) { |
| 290 | if handler == nil { |
| 291 | panic(fmt.Sprintf("chi: attempting to Mount() a nil handler on '%s'", pattern)) |
| 292 | } |
| 293 | |
| 294 | // Provide runtime safety for ensuring a pattern isn't mounted on an existing |
| 295 | // routing pattern. |
| 296 | if mx.tree.findPattern(pattern+"*") || mx.tree.findPattern(pattern+"/*") { |
| 297 | panic(fmt.Sprintf("chi: attempting to Mount() a handler on an existing path, '%s'", pattern)) |
| 298 | } |
| 299 | |
| 300 | // Assign sub-Router's with the parent not found & method not allowed handler if not specified. |
| 301 | subr, ok := handler.(*Mux) |
| 302 | if ok && subr.notFoundHandler == nil && mx.notFoundHandler != nil { |
| 303 | subr.NotFound(mx.notFoundHandler) |
| 304 | } |
| 305 | if ok && subr.methodNotAllowedHandler == nil && mx.methodNotAllowedHandler != nil { |
| 306 | subr.MethodNotAllowed(mx.methodNotAllowedHandler) |
| 307 | } |
| 308 | |
| 309 | mountHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 310 | rctx := RouteContext(r.Context()) |
| 311 | |
| 312 | // shift the url path past the previous subrouter |
| 313 | rctx.RoutePath = mx.nextRoutePath(rctx) |
| 314 | |
| 315 | // reset the wildcard URLParam which connects the subrouter |
| 316 | n := len(rctx.URLParams.Keys) - 1 |
| 317 | if n >= 0 && rctx.URLParams.Keys[n] == "*" && len(rctx.URLParams.Values) > n { |
| 318 | rctx.URLParams.Values[n] = "" |
| 319 | } |
| 320 | |
| 321 | handler.ServeHTTP(w, r) |
| 322 | }) |
| 323 | |
| 324 | if pattern == "" || pattern[len(pattern)-1] != '/' { |
| 325 | mx.handle(mALL|mSTUB, pattern, mountHandler) |
| 326 | mx.handle(mALL|mSTUB, pattern+"/", mountHandler) |
| 327 | pattern += "/" |
| 328 | } |
| 329 | |
| 330 | method := mALL |
| 331 | subroutes, _ := handler.(Routes) |
| 332 | if subroutes != nil { |
| 333 | method |= mSTUB |
| 334 | } |
| 335 | n := mx.handle(method, pattern+"*", mountHandler) |
| 336 | |
| 337 | if subroutes != nil { |
| 338 | n.subroutes = subroutes |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | // Routes returns a slice of routing information from the tree, |
| 343 | // useful for traversing available routes of a router. |