golang项目基础结构
介绍
自己golang项目所需要使用到的基本库,包含 gin、gorm、redis、validate 库。
目的在于将重复的注册验证之类的代码抽离为公共的库以减少资源占用
github.com/gin-gonic/gin v1.9.1
github.com/go-playground/validator/v10 v10.16.0
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/redis/go-redis/v9 v9.3.0
gorm.io/driver/mysql v1.5.2
gorm.io/gorm
使用方式
快速注册配置好的库,推荐在 init
周期中进行注册调用
package comm
import (
"context"
"fmt"
"os"
"time"
"gitee.com/tzrex/freely-handle/before"
dbtype "gitee.com/tzrex/freely-handle/enum/database"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
var (
Gin *gin.Engine
Db *before.DatabaseConnect
Mysql *gorm.DB
RedisCli *redis.Client
)
var (
dbPath string
redisPath string
)
// 注册模板
func init() {
initGin() // 注册 gin
initMysql() // 注册mysql
initRedis() // 注册redis
initValid() // 注册字段验证
}
func initMysql() {
// 连接mysql
Mysql = before.NewConnectionDatabase(&before.ConnectConfigStu{
DbType: dbtype.Mysql,
DbHost: dbPath,
DbPort: "3306",
DbUsername: "demo",
DbPassword: "cfP3S4t5sXnmNJwT",
DbName: "demo",
DbMaxOpenConns: 100,
DbMaxIdleConns: 10,
DbMaxLifetime: time.Hour * 2,
})
if Mysql == nil {
fmt.Println("mysql链接失败")
} else {
fmt.Println("mysql.success")
}
Db = before.NewDatabaseConnect(Mysql)
}
func initRedis() {
// 连接redis
RedisCli = before.NewConnectionRedis(&before.RedisConnetConfigStu{
RedisHost: redisPath,
RedisPort: "6379",
RedisPass: "", // 需要密码时填写
DialTimeout: time.Duration(30) * time.Minute,
ReadTimeout: time.Duration(30) * time.Minute,
})
str, err := RedisCli.Ping(context.TODO()).Result()
if err != nil {
fmt.Println("redis连接失败")
} else {
fmt.Println("redis.ping", str)
}
}
func initGin() {
var isProd bool
if os.Getenv("env") == "production" {
isProd = true
// 改为对应的容器服务名称
dbPath = "mysql"
redisPath = "redis"
} else {
isProd = false
dbPath = "127.0.0.1"
redisPath = "127.0.0.1"
}
// 添加 gin
Gin = before.CreateGin(&before.GinSchema{
IsProd: isProd,
Welcome: "hello.core.handle",
SessionKey: "freely-session",
SessionSecret: "rex-fwfh54g2w45g12s4",
})
fmt.Println("[isProd]: ", isProd)
}
func initValid() {
// 注册validate验证
before.RegisterValidate()
}
之后在 main
包中执行,并完成 init
函数的调用
package main
func main() {
defer func() {
comm.RedisCli.Close()
}()
comm.Gin.Run(":7400")
}
Gin中间件
目前都会用到的中间件,所以把都会用到的中间件写到了公共库中
- 允许跨域:当类型是
OPTIONS
时直接返回 "request.options"
字符串。
- 限流接口:一秒钟最多120个接口,并行10个。
- 错误捕获:捕获项目中意外出现的
pinic
,返回错误码和 500
http状态码。
- 权限校验:过滤
"/"
和 ignore
参数的字符。其余的接口均需要正确的 Authorization
头。