Gin文档地址:https://gin-gonic.com/zh-cn/docs/introduction/
-
我们启动最简单的方式启动Gin服务
package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // 监听并在 0.0.0.0:8080 上启动服务 }
如果这种业务代码都在 main.go 文件中,可想对于后期维护和开发成本巨大。于是呼出现了分层操作。
-
编写我们分层代码
创建 Goft.go 文件,该文件主要用于挂载需要执行的 gin.Handle,启动gin服务
package Goft import "github.com/gin-gonic/gin" type Goft struct { *gin.Engine } func Ignite() *Goft { return &Goft{gin.New()} } //挂载需要执行的 gin.Handle func (g *Goft) Mount(controllers ...IController) *Goft { for _, controller := range controllers { controller.Build(g) } return g } func (g *Goft) Launch(addr string) { if addr == "" { addr = ":8088" } g.Run(addr) }
- 创建 IController.go 目的是批量注册 gin.Handler
package Goft
type IController interface {
Build(g *Goft)
}
- 创建 UserController.go 和 IndexController.go
package Controller
import (
"github.com.filphand/Goft"
"github.com/gin-gonic/gin"
"net/http"
)
type IndexController struct {}
func NewIndexController() *IndexController {
return &IndexController{}
}
func (this *IndexController) GetIndex() gin.HandlerFunc {
return func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"result": "index ok",
})
}
}
func (this *IndexController) Build(g *Goft.Goft) {
g.Handle("GET","/index",this.GetIndex())
}
package Controller
import (
"github.com.filphand/Goft"
"github.com/gin-gonic/gin"
"net/http"
)
type UserController struct {}
func NewUserController() *UserController {
return &UserController{}
}
func (this *UserController) GetList() gin.HandlerFunc {
return func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"result": "index ok",
})
}
}
func (this *UserController) Build(g *Goft.Goft) {
g.Handle("GET","/userController",this.GetList())
}
- 在main.go 执行调用
package main
import (
."github.com.filphand/Controller"
"github.com.filphand/Goft"
)
func main(){
Goft.Ignite().
Mount(
NewIndexController(),
NewUserController()).
Launch(":8088")
}
执行结果:
image.png