批量注册

gf框架的分组路由同时也支持批量的路由注册方式。该方式不是特别常用。

  1. package main
  2. import (
  3. "github.com/gogf/gf/frame/g"
  4. "github.com/gogf/gf/net/ghttp"
  5. )
  6. type Object struct{}
  7. func (o *Object) Show(r *ghttp.Request) {
  8. r.Response.Writeln("Show")
  9. }
  10. func (o *Object) Delete(r *ghttp.Request) {
  11. r.Response.Writeln("REST Delete")
  12. }
  13. func Handler(r *ghttp.Request) {
  14. r.Response.Writeln("Handler")
  15. }
  16. func HookHandler(r *ghttp.Request) {
  17. r.Response.Writeln("HOOK Handler")
  18. }
  19. func main() {
  20. s := g.Server()
  21. obj := new(Object)
  22. s.Group("/api").Bind([]ghttp.GroupItem{
  23. {"ALL", "*", HookHandler, ghttp.HOOK_BEFORE_SERVE},
  24. {"ALL", "/handler", Handler},
  25. {"ALL", "/obj", obj},
  26. {"GET", "/obj/show", obj, "Show"},
  27. {"REST", "/obj/rest", obj},
  28. })
  29. s.SetPort(8199)
  30. s.Run()
  31. }

执行后,终端输出的路由表如下:

  1. SERVER | DOMAIN | ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  2. |---------|---------|---------|--------|-----------------|-----------------------|-------------------|
  3. default | default | :8199 | ALL | /api/* | main.HookHandler | HOOK_BEFORE_SERVE
  4. |---------|---------|---------|--------|-----------------|-----------------------|-------------------|
  5. default | default | :8199 | ALL | /api/handler | main.Handler |
  6. |---------|---------|---------|--------|-----------------|-----------------------|-------------------|
  7. default | default | :8199 | ALL | /api/obj/delete | main.(*Object).Delete |
  8. |---------|---------|---------|--------|-----------------|-----------------------|-------------------|
  9. default | default | :8199 | DELETE | /api/obj/rest | main.(*Object).Delete |
  10. |---------|---------|---------|--------|-----------------|-----------------------|-------------------|
  11. default | default | :8199 | ALL | /api/obj/show | main.(*Object).Show |
  12. |---------|---------|---------|--------|-----------------|-----------------------|-------------------|
  13. default | default | :8199 | GET | /api/obj/show | main.(*Object).Show |
  14. |---------|---------|---------|--------|-----------------|-----------------------|-------------------|