Group routing is the primary routing registration method used in business projects.

Group Routing

The GoFrame framework supports group routing registration. You can specify a prefix for a group route (you can also directly specify the / prefix, which means registering under the root route), and all route registrations under this group will be registered under this route prefix. Group routing registration is also the recommended routing registration method.

API Documentation: https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#RouterGroup

  1. // Create a group route
  2. func (s *Server) Group(prefix string, groups ...func(g *RouterGroup)) *RouterGroup
  3. // Register Method route
  4. func (g *RouterGroup) ALL(pattern string, object interface{}, params...interface{})
  5. func (g *RouterGroup) GET(pattern string, object interface{}, params...interface{})
  6. func (g *RouterGroup) PUT(pattern string, object interface{}, params...interface{})
  7. func (g *RouterGroup) POST(pattern string, object interface{}, params...interface{})
  8. func (g *RouterGroup) DELETE(pattern string, object interface{}, params...interface{})
  9. ...
  10. // Middleware binding
  11. func (g *RouterGroup) Middleware(handlers ...HandlerFunc) *RouterGroup
  12. // Batch registration
  13. func (g *RouterGroup) Map(m map[string]interface{})
  14. func (g *RouterGroup) ALLMap(m map[string]interface{})

Brief Introduction:

  1. The Group method is used to create a group route object and supports creating on a specified domain object.
  2. Methods named after HTTP Method are used to bind specified HTTP Method routes; the ALL method is used to register all HTTP Methods to a specified function/object/controller; the REST method is used to register RESTful style routes, requiring a given executable object or controller object.
  3. The Middleware method is used to bind one or more middleware to the routes of the current group, as detailed in the middleware chapter.

Simple Example

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.Group("/api", func(group *ghttp.RouterGroup) {
  9. group.ALL("/all", func(r *ghttp.Request) {
  10. r.Response.Write("all")
  11. })
  12. group.GET("/get", func(r *ghttp.Request) {
  13. r.Response.Write("get")
  14. })
  15. group.POST("/post", func(r *ghttp.Request) {
  16. r.Response.Write("post")
  17. })
  18. })
  19. s.SetPort(8199)
  20. s.Run()
  21. }

After execution, the terminal prints out the routing table as follows:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|-----------|-----------------|------------|
  3. default | default | :8199 | ALL | /api/all | main.main.func1 |
  4. |---------|---------|---------|--------|-----------|-----------------|------------|
  5. default | default | :8199 | GET | /api/get | main.main.func2 |
  6. |---------|---------|---------|--------|-----------|-----------------|------------|
  7. default | default | :8199 | POST | /api/post | main.main.func3 |
  8. |---------|---------|---------|--------|-----------|-----------------|------------|

Among them, /api/get only allows access via GET, /api/post only allows access via POST, and /api/all allows access via all methods.

We use the curl tool for testing:

  1. /api/get
  1. $ curl http://127.0.0.1:8199/api/get
  2. get
  3. $ curl -X POST http://127.0.0.1:8199/api/get
  4. Not Found
  1. /api/post
  1. $ curl http://127.0.0.1:8199/api/post
  2. Not Found
  3. $ curl -X POST http://127.0.0.1:8199/api/post post
  1. /api/all
  1. $ curl http://127.0.0.1:8199/api/all
  2. all
  3. $ curl -X POST http://127.0.0.1:8199/api/all
  4. all
  5. $ curl -X DELETE http://127.0.0.1:8199/api/all
  6. all
  7. $ curl -X OPTIONS http://127.0.0.1:8199/api/all
  8. all

Hierarchical Registration

Registration - Group Routing - 图1tip

The hierarchical routing registration method of the GoFrame framework is inspired by the PHP Laravel framework. (wink)

It is recommended to use hierarchical route registration; the registered route code is clearer and more intuitive. The GoFrame framework’s group routing registration supports a more intuitive and elegant hierarchical registration method for developers to manage route lists more conveniently. Hierarchical route registration is also the recommended routing registration method. Let’s look at a more comprehensive example where middleware, HOOK, and routes bound to different HTTP Methods are used:

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/net/ghttp"
  7. )
  8. func MiddlewareAuth(r *ghttp.Request) {
  9. if r.Get("token").String() != "123456" {
  10. r.Response.WriteStatus(http.StatusForbidden)
  11. return
  12. }
  13. r.Middleware.Next()
  14. }
  15. func MiddlewareCORS(r *ghttp.Request) {
  16. r.Response.CORSDefault()
  17. r.Middleware.Next()
  18. }
  19. func MiddlewareLog(r *ghttp.Request) {
  20. r.Middleware.Next()
  21. fmt.Println(r.Response.Status, r.URL.Path)
  22. }
  23. func main() {
  24. s := g.Server()
  25. s.Use(MiddlewareLog)
  26. s.Group("/api.v2", func(group *ghttp.RouterGroup) {
  27. group.Middleware(MiddlewareAuth, MiddlewareCORS)
  28. group.GET("/test", func(r *ghttp.Request) {
  29. r.Response.Write("test")
  30. })
  31. group.Group("/order", func(group *ghttp.RouterGroup) {
  32. group.GET("/list", func(r *ghttp.Request) {
  33. r.Response.Write("list")
  34. })
  35. group.PUT("/update", func(r *ghttp.Request) {
  36. r.Response.Write("update")
  37. })
  38. })
  39. group.Group("/user", func(group *ghttp.RouterGroup) {
  40. group.GET("/info", func(r *ghttp.Request) {
  41. r.Response.Write("info")
  42. })
  43. group.POST("/edit", func(r *ghttp.Request) {
  44. r.Response.Write("edit")
  45. })
  46. group.DELETE("/drop", func(r *ghttp.Request) {
  47. r.Response.Write("drop")
  48. })
  49. })
  50. group.Group("/hook", func(group *ghttp.RouterGroup) {
  51. group.Hook("/*", ghttp.HookBeforeServe, func(r *ghttp.Request) {
  52. r.Response.Write("hook any")
  53. })
  54. group.Hook("/:name", ghttp.HookBeforeServe, func(r *ghttp.Request) {
  55. r.Response.Write("hook name")
  56. })
  57. })
  58. })
  59. s.SetPort(8199)
  60. s.Run()
  61. }

After execution, the registered route list looks like this:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  3. default | default | :8199 | ALL | /* | main.MiddlewareLog | GLOBAL MIDDLEWARE
  4. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  5. default | default | :8199 | ALL | /api.v2/hook/* | main.main.func1.4.1 | HOOK_BEFORE_SERVE
  6. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  7. default | default | :8199 | ALL | /api.v2/hook/:name | main.main.func1.4.2 | HOOK_BEFORE_SERVE
  8. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  9. default | default | :8199 | GET | /api.v2/order/list | main.main.func1.2.1 | main.MiddlewareAuth,main.MiddlewareCORS
  10. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  11. default | default | :8199 | PUT | /api.v2/order/update | main.main.func1.2.2 | main.MiddlewareAuth,main.MiddlewareCORS
  12. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  13. default | default | :8199 | GET | /api.v2/test | main.main.func1.1 | main.MiddlewareAuth,main.MiddlewareCORS
  14. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  15. default | default | :8199 | DELETE | /api.v2/user/drop | main.main.func1.3.3 | main.MiddlewareAuth,main.MiddlewareCORS
  16. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  17. default | default | :8199 | POST | /api.v2/user/edit | main.main.func1.3.2 | main.MiddlewareAuth,main.MiddlewareCORS
  18. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|
  19. default | default | :8199 | GET | /api.v2/user/info | main.main.func1.3.1 | main.MiddlewareAuth,main.MiddlewareCORS
  20. |---------|---------|---------|--------|----------------------|---------------------|-----------------------------------------|

Batch Registration

Map

The Map method can be used for batch group route registration, but for the same URI with different HTTP Methods, you need to specify the HTTP Method according to route conventions. Example usage:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func UserGet(r *ghttp.Request) {
  7. r.Response.Write("get")
  8. }
  9. func UserDelete(r *ghttp.Request) {
  10. r.Response.Write("delete")
  11. }
  12. func main() {
  13. s := g.Server()
  14. s.Group("/api", func(group *ghttp.RouterGroup) {
  15. group.Map(g.Map{
  16. "GET: /user": UserGet,
  17. "DELETE: /user": UserDelete,
  18. })
  19. })
  20. s.SetPort(8199)
  21. s.Run()
  22. }

AllMap

You can also use the ALLMap method for batch group route registration. Routes registered through this method will apply the route function/object to all HTTP Methods. Example usage:

  1. s := g.Server()
  2. // Routing registration for the front-end system
  3. s.Group("/", func(group *ghttp.RouterGroup) {
  4. group.Middleware(service.Middleware.Ctx)
  5. group.ALLMap(g.Map{
  6. "/": api.Index, // Home
  7. "/login": api.Login, // Login
  8. "/register": api.Register, // Register
  9. "/category": api.Category, // Category
  10. "/topic": api.Topic, // Topic
  11. "/topic/:id": api.Topic.Detail, // Topic - Detail
  12. "/ask": api.Ask, // Q&A
  13. "/ask/:id": api.Ask.Detail, // Q&A - Detail
  14. "/article": api.Article, // Article
  15. "/article/:id": api.Article.Detail, // Article - Detail
  16. "/reply": api.Reply, // Reply
  17. "/search": api.Search, // Search
  18. "/captcha": api.Captcha, // Captcha
  19. "/user/:id": api.User.Index, // User - Home
  20. })
  21. // Permission control routes
  22. group.Group("/", func(group *ghttp.RouterGroup) {
  23. group.Middleware(service.Middleware.Auth)
  24. group.ALLMap(g.Map{
  25. "/user": api.User, // User
  26. "/content": api.Content, // Content
  27. "/interact": api.Interact, // Interact
  28. "/file": api.File, // File
  29. })
  30. })
  31. })