Router: add prefix group interface and implementation

This commit is contained in:
Muyao CHEN 2024-09-16 12:04:27 +02:00
parent 5cb54ae560
commit d90e564620
3 changed files with 53 additions and 0 deletions

View File

@ -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")

43
framework/group.go Normal file
View File

@ -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)
}

View File

@ -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)
}