一个可以简化Gin分层的骚操作

Gin文档地址:https://gin-gonic.com/zh-cn/docs/introduction/

  1. 我们启动最简单的方式启动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 文件中,可想对于后期维护和开发成本巨大。于是呼出现了分层操作。

  1. 编写我们分层代码

    创建 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)
    }
    
    1. 创建 IController.go 目的是批量注册 gin.Handler
package Goft

type IController interface {
   Build(g *Goft)
}
  1. 创建 UserController.goIndexController.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())
}
  1. main.go 执行调用
package main

import (
   ."github.com.filphand/Controller"
   "github.com.filphand/Goft"
)

func main(){
   Goft.Ignite().
      Mount(
         NewIndexController(),
         NewUserController()).
      Launch(":8088")
}

执行结果:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容