1
0
Fork 0

Sub-path implemented, now you can make a sub for a section using Router's Sub(root) method and then write only what this section contains. Like s := Sub("/api/v1") and then s.Handler("/").

This commit is contained in:
Alexander Andreev 2023-08-11 18:42:28 +04:00
parent 0717a2e3d3
commit 3cb32c5ec9
Signed by: Arav
GPG Key ID: D22A817D95815393
1 changed files with 28 additions and 0 deletions

View File

@ -212,6 +212,34 @@ func (rr *Router) ServeStatic(path string, root http.FileSystem) error {
})
}
// subPath contains a root path that is being attached in front of a pattern
// passed by a Handler() func.
type subPath struct {
r *Router
root string
}
// Sub returns a sub-path with a root path, after that you can shorten patterns.
//
// E.g. instead of writing each time "/api/something/other" create a
// sub-router with a root path "/api/something" and then pass just "/other" in
// a Handler() func of subPath struct.
func (rr *Router) Sub(root string) *subPath {
if root[len(root)-1] == '/' {
root = root[:len(root)-1]
}
return &subPath{
r: rr,
root: root,
}
}
// Handler attaches root path to a given pattern and pass it to a router.
func (sp *subPath) Handler(method, pattern string, handler http.HandlerFunc) error {
return sp.r.Handler(method, sp.root+pattern, handler)
}
// Param returns a URL parameter (that is set like `/a/b/:key/d`) with a key
// or an empty string if no such parameter found.
func Param(r *http.Request, key string) string {