Skip to main content
Version: 2.8.x(Latest)

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:

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

Examples

Hello World

Let's look at a simple example:

package main

import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)

func main() {
s := g.Server()
s.BindHandler("/", func(r *ghttp.Request) {
r.Response.Write("Hello World!")
})
s.SetPort(8199)
s.Run()
}

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:

package main

import (
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)

var (
total = gtype.NewInt()
)

func Total(r *ghttp.Request) {
r.Response.Write("total:", total.Add(1))
}

func main() {
s := g.Server()
s.BindHandler("/total", Total)
s.SetPort(8199)
s.Run()
}

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:

package main

import (
"github.com/gogf/gf/v2/container/gtype"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)

type Controller struct {
total *gtype.Int
}

func (c *Controller) Total(r *ghttp.Request) {
r.Response.Write("total:", c.total.Add(1))
}

func main() {
s := g.Server()
c := &Controller{
total: gtype.NewInt(),
}
s.BindHandler("/total", c.Total)
s.SetPort(8199)
s.Run()
}

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.