github
接上篇
接口数据时间格式
在上篇 整合mysql ---gorm框架部分 返回数据的时间格式是带时区的 一般我们需要把他转成 2006-01-02 15:04:05 这种格式
http://localhost:1016/user/save?username=aaa
{“code”:200,“data”:{“ID”:3,“CreatedAt”:“2023-02-13T10:40:26.2750692+08:00”,“UpdatedAt”:“2023-02-13T10:40:26.2750692+08:00”,“DeletedAt”:null,“Username”:“aaa”,“Password”:“”,“Tel”:“”}}
-
定义一个时间类型,来重写时间格式为我们需要的格式
/model/BaseModel.go
package model
import (
"database/sql/driver"
"fmt"
"time"
)
type BaseModel struct {
ID uint `gorm:"primary_key"`
CreatedAt *FormatTime
UpdatedAt *FormatTime
DeletedAt *FormatTime `sql:"index"`
}
type FormatTime time.Time
func (t *FormatTime) MarshalJSON() ([]byte, error) {
tTime := time.Time(*t)
return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
}
func (t FormatTime) Value() (driver.Value, error) {
tTime := time.Time(t)
return tTime.Format("2006-01-02 15:04:05"), nil
}
func (t *FormatTime) Scan(v interface{}) error {
switch vt := v.(type) {
case time.Time:
*t = FormatTime(vt)
}
return nil
}
-
应用
/model/User.go 把原来使用的 gorm.Model 替换为我们的BaseModel
package model
type User struct {
BaseModel
Username string
Password string
Tel string
}
- 测试
-
postman请求 http://localhost:1016/user/save { "code": 200, "data": { "ID": 9, "CreatedAt": "2023-02-14 17:28:59", "UpdatedAt": "2023-02-14 17:28:59", "DeletedAt": null, "Username": "asd", "Password": "", "Tel": "" }, "msg": "success" }
token校验中间件
大部分项目接口中,对接口访问是有身份&权限校验的
/middleware/TokenMiddleware.go
package middleware
import (
"github.com/gin-gonic/gin"
"pro/response"
"strings"
)
func TokenMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
//检查放行白名单
url := c.Request.RequestURI
if CheckWhitelist(url) {
return
}
//验证token
token := c.GetHeader("token")
if CheckToken(token) {
return
}
response.Fail(c, "token失效")
//终止请求执行
c.Abort()
}
}
// 放行白名单 配置具体接口/群组
var Whitelist = []string{
"/user/ggt",
"/rel/",
}
// 检查接口是否需要放行
func CheckWhitelist(url string) bool {
for _, item := range Whitelist {
if url == item || (strings.HasSuffix(item, "/") && strings.HasPrefix(url, item)) {
return true
}
}
return false
}
// 校验token token校验及权限校验在此处处理
func CheckToken(token string) bool {
if token == "123" {
return true
}
return false
}
- main入口 启用中间件
func Router() *gin.Engine {
//禁用gin输出
gin.DefaultWriter = io.Discard
r := gin.Default()
//文件上传大小
r.MaxMultipartMemory = 8 << 20 // 8 MiB
r.Use(
//异常处理
middleware.RecoveryMiddleware(),
//跨域
middleware.CORSMiddleware(),
//请求参数处理
middleware.RequestParamsMiddleware(),
//日志
middleware.LogMiddle(),
//token
middleware.TokenMiddleware(),
)
return StartRouter(r)
}
- 路由配置
func StartRouter(r *gin.Engine) *gin.Engine {
//用户
user := r.Group("/user")
{
user.POST("/save", controller.SaveUser)
user.POST("/del", controller.DelUser)
user.POST("/get", controller.GetUser)
user.POST("/ggt", controller.GetUser)
user.GET("/gg", controller.GG)
}
rel := r.Group("/rel")
{
rel.POST("/get", controller.GetUser)
}
return r
}
-
测试
postman http://localhost:1016/user/get { "code": 400, "data": null, "msg": "token失效" } http://localhost:1016/user/ggt { "code": 200, "data": { "ID": 0, "CreatedAt": null, "UpdatedAt": null, "DeletedAt": null, "Username": "", "Password": "", "Tel": "" }, "msg": "success" } http://localhost:1016/rel/get { "code": 200, "data": { "ID": 0, "CreatedAt": null, "UpdatedAt": null, "DeletedAt": null, "Username": "", "Password": "", "Tel": "" }, "msg": "success" }
多平台打包
选择下方Assets中goreleaser_Windows_x86_64.zip
下载解压后配置环境变量,将路径添加到path中 如: E:\goreleaser_Windows_x86_64
-
打包配置
与main.go同级别 /.goreleaser.yaml
# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
before:
hooks:
# You may remove this if you don't use go modules.
- go mod tidy
# you may remove this if you don't need go generate
- go generate ./...
builds:
- env:
- CGO_ENABLED=0
goos:
- linux
# - windows
# - darwin
archives:
- replacements:
# darwin: Darwin
linux: Linux
# windows: Windows
# 386: i386
amd64: x86_64
checksum:
name_template: 'checksums.txt'
snapshot:
name_template: "{{ incpatch .Version }}-next"
changelog:
sort: asc
filters:
exclude:
- '^docs:'
- '^test:'
# modelines, feel free to remove those if you don't want/use them:
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
-
打包
-
goland打开terminal 执行以下命令 goreleaser --snapshot --skip-publish --rm-dist 等待打包完成 包会成为在/dist目录 /dist/golang_linux_amd64_v1/pro
-
启动
chmod +x pro nohup ./pro>log.log 2>&1 &