模块内部变量形式对象内部变量形式
func (s *Server) BindHandler(pattern string, handler interface{})
BindHandler


示例:

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("哈喽世界!")
    })
    s.SetPort(8199)
    s.Run()
}


包方法注册

注册的路由函数可以是一个包方法:

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()
}
totalgtype.Int

对象方法注册

注册的路由函数可以是一个对象的方法:

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