• Golang学习日志 ━━ Gin-Vue-Admin按步骤手动创建api及router、service


    gin-vue-admin是一套国人用golang开发的后台管理系统,最新版本的系统工具中已经自带自动化package功能,本文记录的是手动创建过程。
    官网:https://www.gin-vue-admin.com/
    学习视频:https://www.bilibili.com/video/BV1kv4y1g7nT/?p=6

    准备工作

    server/api/v1server/routerserver/service目录下创建自己的文件夹及文件。
    本例目录及文件命名都为myTest/enter.gomyTest/my_test1.go,包名都为myTestPkg
    在这里插入图片描述

    数据模块

    如果涉及数据库,那么就需要在model目录下根据gorm规则配置数据结构;如果没有数据库,那么本节略过。

    server/model/myTest/test.go
    package myTestPkg
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/global"
    	"time"
    )
    
    // Test 结构体
    type Test struct {
          global.GVA_MODEL
          Title  string `json:"title" form:"title" gorm:"column:title;comment:;size:255;"`
          Content  string `json:"content" form:"content" gorm:"column:content;comment:;"`
          Showtime  *time.Time `json:"showtime" form:"showtime" gorm:"column:showtime;comment:;"`
    }
    
    
    // TableName Test 表名
    func (Test) TableName() string {
      return "test"
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    server/model/myTest/request/test.go
    package request
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/model/myTest"
    	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
    	"time"
    )
    
    type TestSearch struct{
        myTestPkg.Test
        StartCreatedAt *time.Time `json:"startCreatedAt" form:"startCreatedAt"`
        EndCreatedAt   *time.Time `json:"endCreatedAt" form:"endCreatedAt"`
        request.PageInfo
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    功能服务

    server/service/myTest/enter.go
    package myTestPkg
    
    type ServiceGroup struct {
    	MyTest1Service
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    server/service/myTest/my_test1.go
    package myTestPkg
    
    import (
    	"fmt"
    )
    
    type MyTest1Service struct {
    }
    
    func (s *MyTest1Service) CreateService() {
    	fmt.Print("这里仅执行打印")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    server/service/enter.go
    package service
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/service/example"
    	"github.com/flipped-aurora/gin-vue-admin/server/service/myTest"
    	"github.com/flipped-aurora/gin-vue-admin/server/service/system"
    )
    
    type ServiceGroup struct {
    	SystemServiceGroup  system.ServiceGroup
    	ExampleServiceGroup example.ServiceGroup
    	MyTestServiceGroup  myTestPkg.ServiceGroup
    }
    
    var ServiceGroupApp = new(ServiceGroup)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    API

    server/api/v1/myTest/enter.go
    package myTestPkg
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/service"
    )
    
    type ApiGroup struct {
    	MyTest1Api
    }
    
    var (
    	myTestService = service.ServiceGroupApp.MyTestServiceGroup.MyTest1Service
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    server/api/v1/myTest/my_test1.go
    package myTestPkg
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
    	"github.com/gin-gonic/gin"
    )
    
    type MyTest1Api struct {
    }
    
    func (m *MyTest1Api) CreateApi(c *gin.Context) {
    	myTestService.CreateService()
    
    	response.Ok(c)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    server/api/v1/enter.go
    package v1
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/api/v1/example"
    	"github.com/flipped-aurora/gin-vue-admin/server/api/v1/myTest"
    	"github.com/flipped-aurora/gin-vue-admin/server/api/v1/system"
    )
    
    type ApiGroup struct {
    	SystemApiGroup  system.ApiGroup
    	ExampleApiGroup example.ApiGroup
    	MyTestApiGroup  myTestPkg.ApiGroup
    }
    
    var ApiGroupApp = new(ApiGroup)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    路由

    server/router/myTest/enter.go
    package myTestPkg
    
    type RouterGroup struct {
    	MyTest1Router
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    server/router/myTest/my_test1.go
    package myTestPkg
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/api/v1"
    	"github.com/flipped-aurora/gin-vue-admin/server/middleware"
    	"github.com/gin-gonic/gin"
    )
    
    type MyTest1Router struct {
    }
    
    // InitMyTest1Router 初始化 MyTest1 路由信息
    func (s *MyTest1Router) InitMyTest1Router(Router *gin.RouterGroup) {
    	myTest1Router := Router.Group("myTest1").Use(middleware.OperationRecord())
    
    	var myTest1Api = v1.ApiGroupApp.MyTestApiGroup.MyTest1Api
    	{
    		myTest1Router.POST("createMyTest1Api", myTest1Api.CreateApi)
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    server/router/enter.go
    package router
    
    import (
    	"github.com/flipped-aurora/gin-vue-admin/server/router/example"
    	"github.com/flipped-aurora/gin-vue-admin/server/router/myTest"
    	"github.com/flipped-aurora/gin-vue-admin/server/router/system"
    )
    
    type RouterGroup struct {
    	System            system.RouterGroup
    	Example           example.RouterGroup
    	MyTestRouterGroup myTestPkg.RouterGroup
    }
    
    var RouterGroupApp = new(RouterGroup)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    初始化

    server/initialize/router.go
    package initialize
    
    import (
    	"net/http"
    
    	_ "github.com/flipped-aurora/gin-vue-admin/server/docs"
    	"github.com/flipped-aurora/gin-vue-admin/server/global"
    	"github.com/flipped-aurora/gin-vue-admin/server/middleware"
    	"github.com/flipped-aurora/gin-vue-admin/server/router"
    	"github.com/gin-gonic/gin"
    	"github.com/swaggo/gin-swagger"
    	"github.com/swaggo/gin-swagger/swaggerFiles"
    )
    
    // 初始化总路由
    
    func Routers() *gin.Engine {
    	Router := gin.Default()
    	myTestRouter := router.RouterGroupApp.MyTestRouterGroup
    	systemRouter := router.RouterGroupApp.System
    	exampleRouter := router.RouterGroupApp.Example
    
    	Router.StaticFS(global.GVA_CONFIG.Local.Path, http.Dir(global.GVA_CONFIG.Local.StorePath)) // 为用户头像和文件提供静态地址
    	Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
    	global.GVA_LOG.Info("register swagger handler")
    	// 方便统一添加路由组前缀 多服务器上线使用
    
    	PublicGroup := Router.Group("")
    	{
    		// 健康监测
    		PublicGroup.GET("/health", func(c *gin.Context) {
    			c.JSON(200, "ok")
    		})
    	}
    	{
    		systemRouter.InitBaseRouter(PublicGroup) // 注册基础功能路由 不做鉴权
    		systemRouter.InitInitRouter(PublicGroup) // 自动初始化相关
    	}
    	PrivateGroup := Router.Group("")
    	PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
    	{
    		systemRouter.InitApiRouter(PrivateGroup)                 // 注册功能api路由
    		systemRouter.InitJwtRouter(PrivateGroup)                 // jwt相关路由
    		systemRouter.InitUserRouter(PrivateGroup)                // 注册用户路由
    		systemRouter.InitMenuRouter(PrivateGroup)                // 注册menu路由
    		systemRouter.InitSystemRouter(PrivateGroup)              // system相关路由
    		systemRouter.InitCasbinRouter(PrivateGroup)              // 权限相关路由
    		systemRouter.InitAutoCodeRouter(PrivateGroup)            // 创建自动化代码
    		systemRouter.InitAuthorityRouter(PrivateGroup)           // 注册角色路由
    		systemRouter.InitSysDictionaryRouter(PrivateGroup)       // 字典管理
    		systemRouter.InitAutoCodeHistoryRouter(PrivateGroup)     // 自动化代码历史
    		systemRouter.InitSysOperationRecordRouter(PrivateGroup)  // 操作记录
    		systemRouter.InitSysDictionaryDetailRouter(PrivateGroup) // 字典详情管理
    		systemRouter.InitAuthorityBtnRouterRouter(PrivateGroup)  // 字典详情管理
    
    		exampleRouter.InitExcelRouter(PrivateGroup)                 // 表格导入导出
    		exampleRouter.InitCustomerRouter(PrivateGroup)              // 客户路由
    		exampleRouter.InitFileUploadAndDownloadRouter(PrivateGroup) // 文件上传下载功能路由
    
    		myTestRouter.InitMyTest1Router(PrivateGroup)
    	}
    
    	InstallPlugin(Router) // 安装插件
    
    	global.GVA_LOG.Info("router register success")
    	return Router
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    server/initialize/gorm.go

    如果涉及数据库,在model中配置完后,可以在这里注册数据库。

    package initialize
    
    import (
    	"os"
    
    	"github.com/flipped-aurora/gin-vue-admin/server/global"
    	"github.com/flipped-aurora/gin-vue-admin/server/model/example"
    	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
    	"github.com/flipped-aurora/gin-vue-admin/server/model/test"
    
    	"go.uber.org/zap"
    	"gorm.io/gorm"
    )
    
    // Gorm 初始化数据库并产生数据库全局变量
    // Author SliverHorn
    func Gorm() *gorm.DB {
    	switch global.GVA_CONFIG.System.DbType {
    	case "mysql":
    		return GormMysql()
    	case "pgsql":
    		return GormPgSql()
    	case "oracle":
    		return GormOracle()
      case "mssql":
    		return GormMssql()
    	default:
    		return GormMysql()
    	}
    }
    
    // RegisterTables 注册数据库表专用
    // Author SliverHorn
    func RegisterTables(db *gorm.DB) {
    	err := db.AutoMigrate(
    		// 系统模块表
    		system.SysApi{},
    		system.SysUser{},
    		system.SysBaseMenu{},
    		system.JwtBlacklist{},
    		system.SysAuthority{},
    		system.SysDictionary{},
    		system.SysOperationRecord{},
    		system.SysAutoCodeHistory{},
    		system.SysDictionaryDetail{},
    		system.SysBaseMenuParameter{},
    		system.SysBaseMenuBtn{},
    		system.SysAuthorityBtn{},
    		system.SysAutoCode{},
    
    		// 示例模块表
    		example.ExaFile{},
    		example.ExaCustomer{},
    		example.ExaFileChunk{},
    		example.ExaFileUploadAndDownload{},
    
    		// 测试模块表
    		myTestPkg.Test{},
    
    		// 自动化模块表
    		// Code generated by github.com/flipped-aurora/gin-vue-admin/server Begin; DO NOT EDIT.
    
    		// Code generated by github.com/flipped-aurora/gin-vue-admin/server End; DO NOT EDIT.
    	)
    	if err != nil {
    		global.GVA_LOG.Error("register table failed", zap.Error(err))
    		os.Exit(0)
    	}
    	global.GVA_LOG.Info("register table success")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    server/initialize/plugin.go

    如果开发了plugin插件,那么也别忘了初始化

    package initialize
    
    import (
    	"fmt"
    
    	"github.com/flipped-aurora/gin-vue-admin/server/global"
    	"github.com/flipped-aurora/gin-vue-admin/server/middleware"
    	"github.com/flipped-aurora/gin-vue-admin/server/plugin/email"
    
    	"github.com/flipped-aurora/gin-vue-admin/server/utils/plugin"
    	"github.com/gin-gonic/gin"
    )
    
    func PluginInit(group *gin.RouterGroup, Plugin ...plugin.Plugin) {
    	for i := range Plugin {
    		PluginGroup := group.Group(Plugin[i].RouterPath())
    		Plugin[i].Register(PluginGroup)
    	}
    }
    
    func InstallPlugin(Router *gin.Engine) {
    	PublicGroup := Router.Group("")
    	fmt.Println("无鉴权插件安装==》", PublicGroup)
    	PrivateGroup := Router.Group("")
    	fmt.Println("鉴权插件安装==》", PrivateGroup)
    	PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
    	//  添加跟角色挂钩权限的插件 示例 本地示例模式于在线仓库模式注意上方的import 可以自行切换 效果相同
    	PluginInit(PrivateGroup, email.CreateEmailPlug(
    		global.GVA_CONFIG.Email.To,
    		global.GVA_CONFIG.Email.From,
    		global.GVA_CONFIG.Email.Host,
    		global.GVA_CONFIG.Email.Secret,
    		global.GVA_CONFIG.Email.Nickname,
    		global.GVA_CONFIG.Email.Port,
    		global.GVA_CONFIG.Email.IsSSL,
    	))
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    总结

    代码要求还是很统一的,创建同样的目录文件,放在同一个包下,告诉enter.go有几个组(本文就一个,都是开头用MyTest1命名,比如MyTest1Api),先创建service,再给api调用,然后给router分配,最后initialize初始化路由。

    go build main.go
    
    • 1

    生成执行文件打开后,如图,表示api接口已经对外发布。
    在这里插入图片描述

    在这里插入图片描述

  • 相关阅读:
    【LeetCode】232.用栈实现队列
    Kafka与Spark案例实践
    基于路网层次收缩的快速分布式地图匹配算法
    1519_AURIX TC275 SRI总线部分相关寄存器的梳理
    IDEA 对单个的java class文件打成jar包
    [附源码]计算机毕业设计JAVA教师档案管理系统
    【学习记录】调试千寻服务+DTU+导远RTK过程的记录
    某60区块链安全之不安全的随机数实战二学习记录
    java JVM原理与常识知识点
    GBase 8d的特性-可扩展性
  • 原文地址:https://blog.csdn.net/snans/article/details/127886291