goframe 版本2.4.1
根据官网自建goframe项目,下面根据demo新模块说明
分组路由中间件
g.Server().Group一般用来做分组路由,通过规则来分流每个请求,然后在Group里面用到group.Middleware调用中间件
全局路由中间件
后期新增的模块有改动,可能也会需要用到g.Server().Group这个功能,但是为了解耦,不想入侵原来的核心文件,可以在新增的模块的中间件使用g.Server().BindMiddleware
目录结构
main.go
引入新增的模块
package main
import (
"github.com/gogf/gf/os/gctx"
// 引入新增的模块
_ "gfdemo/demo"
_ "gfdemo/internal/logic"
_ "gfdemo/internal/packed"
"gfdemo/internal/cmd"
)
func main() {
cmd.Main.Run(gctx.New())
}
demo/controller/controller.go
package controller
import (
"context"
"gfdemo/demo/middleware"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func init() {
controller := &Controller{}
s := g.Server()
s.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(middleware.MiddlewareHandlerResponse)
group.Bind(
controller,
)
})
}
type Controller struct{}
type WelcomeReq struct {
g.Meta `path:"/app/demo/open/welcome" method:"GET"`
}
type WelcomeRes struct {
Data interface{} `json:"data"`
Show interface{} `json:"show"`
}
func (c *Controller) Welcome(ctx context.Context, req *WelcomeReq) (res *WelcomeRes, err error) {
fmt.Println("执行了 /app/demo/open/welcome")
return
}
type MiddReq struct {
g.Meta `path:"/app/demo/comm/Show" method:"GET"`
}
type MiddRes struct {
Data interface{} `json:"data"`
Show interface{} `json:"show"`
}
func (c *Controller) Show(ctx context.Context, req *MiddReq) (res *MiddRes, err error) {
// 如果被全局中间件拦截了,不会打印
fmt.Println("执行了 /app/demo/open/welcome")
return
}
demo/middleware/middleware.go
package middleware
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
// group路由拦截请求
func MiddlewareHandlerResponse(r *ghttp.Request) {
r.Middleware.Next()
type DefaultHandlerResponse struct {
Code int `json:"code" dc:"Error code"`
Message string `json:"message" dc:"Error message"`
Data interface{} `json:"data,omitempty" dc:"Result data for certain request according API definition"`
}
//分组路由中间件返回信息
r.Response.WriteJson(DefaultHandlerResponse{
Code: 1000,
Message: "分组路由中间件",
})
}
func init() {
// 全局路由拦截符合规则的请求
g.Server().BindMiddleware("/app/*/comm/* ", MiddlewareOpen)
}
// 全局路由拦截请求返回
func MiddlewareOpen(r *ghttp.Request) {
statusCode := 200
r.Response.WriteStatusExit(statusCode, g.Map{
"code": 1000,
"message": "全局路由拦截了",
})
r.Middleware.Next()
}
终端输入
go mod tidy
gf run main.go
浏览器打开http://localhost:8100/app/demo/open/welcome
这个是分组路由的请求
浏览器打开http://localhost:8100/app/demo/comm/show
这个是全局路由的请求