Files
common/utils/utils.go
2026-03-12 08:50:45 +08:00

95 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package utils
import (
"context"
"fmt"
"reflect"
"time"
"gitee.com/red-future---jilin-g/common/do"
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
"github.com/tiger1103/gfast-token/gftoken"
)
// ValidStructPtr 验证是否为结构体指针
func ValidStructPtr(req any) (err error) {
//验证请求参数必须为指针
var (
reflectValue reflect.Value
reflectKind reflect.Kind
)
if v, ok := req.(reflect.Value); ok {
reflectValue = v
} else {
reflectValue = reflect.ValueOf(req)
}
reflectKind = reflectValue.Kind()
if reflectKind != reflect.Ptr {
err = gerror.NewCode(gcode.CodeInvalidParameter, `the parameter "req" for function Find should type of *struct/*[]struct`)
}
return
}
// GetMonthToday 获取N个月前的某日
func GetMonthToday(t time.Time, month int) time.Time {
// today
fmt.Printf("today: [%s]\n", t)
// 判断天数范围 小于等于28天的计算,覆盖大多数情况
if t.Day() <= 28 {
return t.AddDate(0, -month, 0)
}
// 月份的天数数组
monthDay := [13]int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
// 计算目标所在日期
target := t.AddDate(0, 0, 1-t.Day()).AddDate(0, -month, 0)
// 计算当月最大天数
targetDay := monthDay[target.Month()]
// 计算闰年
if target.Month() == time.February && (target.Year()%400 == 0 || (target.Year()%100 != 0 && target.Year()%4 == 0)) {
targetDay++
}
if t.Day() > targetDay {
return target.AddDate(0, 0, targetDay-1)
}
return target.AddDate(0, 0, t.Day()-1)
}
func GetUserInfo(ctx context.Context) (user do.User, err error) {
redisAddr := g.Cfg().MustGet(ctx, "redis.default.address").String()
gft := gftoken.NewGfToken(
gftoken.WithCacheKey("gfToken:"),
gftoken.WithTimeout(20),
gftoken.WithMaxRefresh(10),
gftoken.WithMultiLogin(true),
//gftoken.WithExcludePaths(g.SliceStr{"/excludeDemo"}),
gftoken.WithGRedisConfig(&gredis.Config{
Address: redisAddr,
Db: 1,
}))
// 解析 token不再忽略错误
data, err := gft.ParseToken(g.RequestFromCtx(ctx))
if err != nil {
return user, gerror.Wrap(err, "token 解析失败")
}
// 检查 data 是否为 nil
if data == nil {
return user, gerror.New("token 数据为空")
}
// 检查 data.Data 是否为 nil
if data.Data == nil {
return user, gerror.New("用户信息为空")
}
dataMap := gconv.Map(data.Data)
user.UserName = dataMap["userName"]
user.TenantId = dataMap["tenantId"]
return
}