From 3cb32c5ec9e2c5331d3a9c19678defe226ef7bba Mon Sep 17 00:00:00 2001 From: "Alexander \"Arav\" Andreev" Date: Fri, 11 Aug 2023 18:42:28 +0400 Subject: [PATCH] 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("/"). --- httpr.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/httpr.go b/httpr.go index 0c12dc5..5dcbef0 100644 --- a/httpr.go +++ b/httpr.go @@ -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 {