From d90e564620dba161cd34eecec3befb0a305c25ee Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Mon, 16 Sep 2024 12:04:27 +0200 Subject: [PATCH] Router: add prefix group interface and implementation --- framework/core.go | 8 ++++++++ framework/group.go | 43 +++++++++++++++++++++++++++++++++++++++++++ routes.go | 2 ++ 3 files changed, 53 insertions(+) create mode 100644 framework/group.go diff --git a/framework/core.go b/framework/core.go index 88dd75e..1d56848 100644 --- a/framework/core.go +++ b/framework/core.go @@ -51,6 +51,7 @@ func (c *Core) Delete(url string, handler ControllerHandler) { c.router["DELETE"][upperUrl] = handler } +// FindRouteByRequest finds route using the request func (c *Core) FindRouteByRequest(r *http.Request) ControllerHandler { upperUri := strings.ToUpper(r.URL.Path) upperMethod := strings.ToUpper(r.Method) @@ -70,6 +71,13 @@ func (c *Core) FindRouteByRequest(r *http.Request) ControllerHandler { return controller } +func (c *Core) Group(prefix string) IGroup { + return &Group{ + core: c, + prefix: prefix, + } +} + // ServeHTTP implements the Handler interface func (c *Core) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Println("Welcome to the Araneae framework") diff --git a/framework/group.go b/framework/group.go new file mode 100644 index 0000000..f07c02f --- /dev/null +++ b/framework/group.go @@ -0,0 +1,43 @@ +package framework + +// IGroup prefix routes +type IGroup interface { + Get(string, ControllerHandler) + Post(string, ControllerHandler) + Put(string, ControllerHandler) + Delete(string, ControllerHandler) +} + +// Group is the implementation of IGroup interface +type Group struct { + core *Core + prefix string +} + +// NewGroup create a new prefix group +func NewGroup(core *Core, prefix string) *Group { + return &Group{ + core: core, + prefix: prefix, + } +} + +// Get is a simple get router of the group +func (g *Group) Get(url string, handler ControllerHandler) { + g.core.Get(g.prefix+url, handler) +} + +// Post is a simple post router of the group +func (g *Group) Post(url string, handler ControllerHandler) { + g.core.Post(g.prefix+url, handler) +} + +// Put is a simple put router of the group +func (g *Group) Put(url string, handler ControllerHandler) { + g.core.Put(g.prefix+url, handler) +} + +// Delete is a simple delete router of the group +func (g *Group) Delete(url string, handler ControllerHandler) { + g.core.Delete(g.prefix+url, handler) +} diff --git a/routes.go b/routes.go index 2aa7fad..d698236 100644 --- a/routes.go +++ b/routes.go @@ -4,4 +4,6 @@ import "git.vinchent.xyz/vinchent/go-web/framework" func registerRouter(core *framework.Core) { core.Get("/foo", FooControllerHandler) + barGroup := core.Group("/bar") + barGroup.Get("/foo", FooControllerHandler) }