Function Registration

Function Registration is the simplest and most flexible way of route registration. The registered route handler can be an instantiated object method address or a package method address. Relevant methods:

  1. func (s *Server) BindHandler(pattern string, handler interface{})

Examples

Hello World

Let’s look at a 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.BindHandler("/", func(r *ghttp.Request) {
  9. r.Response.Write("Hello World!")
  10. })
  11. s.SetPort(8199)
  12. s.Run()
  13. }

After execution, visiting http://127.0.0.1:8199 will display the familiar content.

Package Method Registration

The handler parameter of the registered route function can be a package method, for example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/container/gtype"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. var (
  8. total = gtype.NewInt()
  9. )
  10. func Total(r *ghttp.Request) {
  11. r.Response.Write("total:", total.Add(1))
  12. }
  13. func main() {
  14. s := g.Server()
  15. s.BindHandler("/total", Total)
  16. s.SetPort(8199)
  17. s.Run()
  18. }

In this example, we register the route using a package method. This method returns the total number of accesses. Since it involves concurrent safety, the total variable uses the concurrent-safe type gtype.Int. After execution, by continuously visiting http://127.0.0.1:8199/total, you will see the returned value increment continuously.

Object Method Registration

The handler parameter of the registered route function can be a method of an object, for example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/container/gtype"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. type Controller struct {
  8. total *gtype.Int
  9. }
  10. func (c *Controller) Total(r *ghttp.Request) {
  11. r.Response.Write("total:", c.total.Add(1))
  12. }
  13. func main() {
  14. s := g.Server()
  15. c := &Controller{
  16. total: gtype.NewInt(),
  17. }
  18. s.BindHandler("/total", c.Total)
  19. s.SetPort(8199)
  20. s.Run()
  21. }

This example achieves the same effect as Example 1, but we use an object to encapsulate the variables needed for business logic, registering the corresponding object methods flexibly through route function registration.