github.com/gogf/gf@v1.16.9/.example/net/ghttp/server/hooks/hooks4.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/gogf/gf/frame/g"
     6  	"github.com/gogf/gf/net/ghttp"
     7  )
     8  
     9  func main() {
    10  	s := g.Server()
    11  	// 多事件回调示例,事件1
    12  	pattern1 := "/:name/info"
    13  	s.BindHookHandlerByMap(pattern1, map[string]ghttp.HandlerFunc{
    14  		ghttp.HookBeforeServe: func(r *ghttp.Request) {
    15  			r.SetParam("uid", 1000)
    16  		},
    17  	})
    18  	s.BindHandler(pattern1, func(r *ghttp.Request) {
    19  		r.Response.Write("用户:", r.Get("name"), ", uid:", r.Get("uid"))
    20  	})
    21  
    22  	// 多事件回调示例,事件2
    23  	pattern2 := "/{object}/list/{page}.java"
    24  	s.BindHookHandlerByMap(pattern2, map[string]ghttp.HandlerFunc{
    25  		ghttp.HookBeforeOutput: func(r *ghttp.Request) {
    26  			r.Response.SetBuffer([]byte(
    27  				fmt.Sprintf("通过事件修改输出内容, object:%s, page:%s", r.Get("object"), r.GetRouterString("page"))),
    28  			)
    29  		},
    30  	})
    31  	s.BindHandler(pattern2, func(r *ghttp.Request) {
    32  		r.Response.Write(r.Router.Uri)
    33  	})
    34  	s.SetPort(8199)
    35  	s.Run()
    36  }