pet-house/business/api/common.go

229 lines
8.6 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 api
import (
"crypto/md5"
"encoding/hex"
"github.com/bwmarrin/snowflake"
"github.com/kataras/iris/v12/context"
"go.uber.org/zap"
"io"
"mime/multipart"
"os"
"path/filepath"
"pet-house.com/business/models"
"pet-house.com/core/server/cache"
"pet-house.com/core/server/cron_server"
"pet-house.com/core/server/database"
"pet-house.com/core/server/zap_server"
"strconv"
"time"
)
type Response struct {
Code int `json:"code"` //code
Msg string `json:"msg"` //msg
Data any `json:"data,omitempty"` //数据
}
type ResponseData struct {
Data any `json:"data"` //数据
}
type Error struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
type DefParty struct {
Prefix string
}
var (
ParamError = Error{Code: 201, Msg: "参数错误"}
IllegalError = Error{Code: 202, Msg: "非法请求"}
UserError = Error{Code: 203, Msg: "用户错误"}
TokenError = Error{Code: 204, Msg: "Token失效请重新登录"}
UserNotExistError = Error{Code: 205, Msg: "用户不存在"}
PetNotExistError = Error{Code: 206, Msg: "用户宠物不存在"}
PetBaseNotExistError = Error{Code: 207, Msg: "宠物基础信息不存在"}
UserServiceAddrNotExistError = Error{Code: 207, Msg: "用户服务地址不存在"}
ServiceAddrNotExistError = Error{Code: 208, Msg: "不在服务地址区域,请重新配置地址"}
NotInServiceExistError = Error{Code: 209, Msg: "不在服务范围"}
OrderCreateError = Error{Code: 210, Msg: "订单创建失败"}
LoginError = Error{Code: 211, Msg: "授权登录失败"}
OrderError = Error{Code: 212, Msg: "当前订单无法修改"}
CarNotExistError = Error{Code: 213, Msg: "当前用户未关联车辆"}
OrderExistError = Error{Code: 214, Msg: "订单不存在"}
PetInfoNotDelError = Error{Code: 215, Msg: "当前宠物存在待服务订单,无法删除"}
PetInfoNotUpdateError = Error{Code: 216, Msg: "当前宠物存在待服务订单,无法修改"}
OrderUpdateBalanceNotEnough = Error{Code: 217, Msg: "当前余额不足"}
)
func Success(ctx *context.Context, request any, data any) {
response := Response{200, "success", data}
reqTime, _ := ctx.Values().GetTime("reqTime")
zap_server.ZAPLOG.Info(ctx.Path(), zap.Any("request", request), zap.Any("response", response), zap.Any("costTime", time.Now().Sub(reqTime).Milliseconds()))
write(ctx, response)
}
func (error *Error) Fail(ctx *context.Context, request any) {
zap_server.ZAPLOG.Info(ctx.Path(), zap.Any("request", request), zap.Any("error", error), zap.Any("err", error.Msg))
write(ctx, Error{error.Code, error.Msg})
}
func (error *Error) DefFail(ctx *context.Context, request any, err any) {
zap_server.ZAPLOG.Info(ctx.Path(), zap.Any("request", request), zap.Any("error", error), zap.Any("err", err))
write(ctx, Error{error.Code, err.(string)})
}
func write(ctx *context.Context, resp any) {
ctx.JSON(resp)
}
var NextId, _ = snowflake.NewNode(1)
func genToken(uid int64) string {
uToken, err := cache.GetCacheString("u_uid_token:" + strconv.FormatInt(uid, 10))
if err == nil && len(uToken) > 0 {
return uToken
}
sId := NextId.Generate()
hash := md5.Sum(sId.Bytes())
token := hex.EncodeToString(hash[:])
cache.SetCache("u_token:"+token, uid, time.Hour*24*30)
cache.SetCache("u_uid_token:"+strconv.FormatInt(uid, 10), token, time.Hour*24*30)
return token
}
func GetTokenInfo(token string) string {
uId, _ := cache.GetCacheString("u_token:" + token)
return uId
}
type HeaderBaseInfo struct {
Token string
Uid int64
}
func GetHeaderBaseInfo(ctx *context.Context) HeaderBaseInfo {
token := ctx.GetHeader("X-Token")
uid := ctx.GetHeader("X-U-Id")
_uid, _ := strconv.ParseInt(uid, 10, 64)
return HeaderBaseInfo{
token, _uid,
}
}
type FrontExclude struct {
path string
}
var PetBaseInfoMap map[int]models.PetBaseInfo
var ServiceAddrMap map[int64]models.ServiceAddr
var PetGoodsMap map[string][]models.PetGoods
var GoodsMap map[int64]models.Goods
var CarMap map[int]models.ServiceCar
var ReserveMap map[string]models.ReserveTimeFilter
var AddrServiceMap map[int64]models.AddrServiceTime
func DataInit() {
//--------------------------------------------------宠物基础信息数据---------------------------------------------------------
var petBastInfoList []models.PetBaseInfo
database.Instance().Model(&models.PetBaseInfo{}).Find(&petBastInfoList)
var PetBaseInfoMapC1 = make(map[int]models.PetBaseInfo)
for _, value := range petBastInfoList {
PetBaseInfoMapC1[value.Id] = value
}
PetBaseInfoMap = PetBaseInfoMapC1
zap_server.ZAPLOG.Info("dataInit petBastInfoMap : ", zap.Any("petBastInfoMap", PetBaseInfoMap))
//--------------------------------------------------服务地址数据---------------------------------------------------------
var serviceAddrList []models.ServiceAddr
database.Instance().Model(&models.ServiceAddr{}).Find(&serviceAddrList)
var ServiceAddrMapC1 = make(map[int64]models.ServiceAddr)
for _, value := range serviceAddrList {
ServiceAddrMapC1[value.Id] = value
}
ServiceAddrMap := ServiceAddrMapC1
zap_server.ZAPLOG.Info("dataInit ServiceAddrMap : ", zap.Any("ServiceAddrMap", ServiceAddrMap))
//--------------------------------------------------宠物商品关联数据---------------------------------------------------------
var petGoodsList []models.PetGoods
database.Instance().Model(&models.PetGoods{}).Find(&petGoodsList)
var PetGoodsMapC1 = make(map[string][]models.PetGoods)
for _, value := range petGoodsList {
key := strconv.Itoa(value.Assortment) + strconv.Itoa(value.PetType) + strconv.Itoa(value.Weight) + strconv.Itoa(value.Hair)
if _, ok := PetGoodsMapC1[key]; ok {
PetGoodsMapC1[key] = append(PetGoodsMapC1[key], value)
} else {
PetGoodsMapC1[key] = []models.PetGoods{value}
}
}
PetGoodsMap = PetGoodsMapC1
zap_server.ZAPLOG.Info("dataInit petGoodsMap : ", zap.Any("petGoodsMap", PetGoodsMap))
//--------------------------------------------------商品数据---------------------------------------------------------
var goodsList []models.Goods
database.Instance().Model(&models.Goods{}).Find(&goodsList)
var GoodsMapC1 = make(map[int64]models.Goods)
for _, value := range goodsList {
GoodsMapC1[value.Id] = value
}
GoodsMap = GoodsMapC1
zap_server.ZAPLOG.Info("dataInit GoodsMap : ", zap.Any("GoodsMap", GoodsMap))
var carList []models.ServiceCar
database.Instance().Model(&models.ServiceCar{}).Find(&carList)
var CarMapC1 = make(map[int]models.ServiceCar)
for _, value := range carList {
CarMapC1[value.Id] = value
}
CarMap = CarMapC1
zap_server.ZAPLOG.Info("dataInit CarMap : ", zap.Any("CarMap", CarMap))
var timesList []models.ReserveTimeFilter
database.Instance().Model(&models.ReserveTimeFilter{}).Find(&timesList)
var ReserveMapC1 = make(map[string]models.ReserveTimeFilter)
for _, value := range timesList {
ReserveMapC1[value.Content] = value
}
ReserveMap = ReserveMapC1
zap_server.ZAPLOG.Info("dataInit ReserveMap : ", zap.Any("ReserveMap", ReserveMap))
var serviceTimesList []models.AddrServiceTime
database.Instance().Model(&models.AddrServiceTime{}).Find(&serviceTimesList)
var AddrServiceMapC1 = make(map[int64]models.AddrServiceTime)
for _, value := range serviceTimesList {
AddrServiceMapC1[value.ServiceAddrId] = value
}
AddrServiceMap = AddrServiceMapC1
zap_server.ZAPLOG.Info("dataInit AddrServiceMap : ", zap.Any("AddrServiceMap", AddrServiceMap))
}
func DataCacheJob() {
c, err := cron_server.CronInstance().AddFunc("@every 1m", DataInit)
if err != nil {
zap_server.ZAPLOG.Info("DataCacheJob err : ", zap.Any("err", err))
}
zap_server.ZAPLOG.Info("DataCacheJob c : ", zap.Any("c", c), zap.Any("err", err))
cron_server.CronInstance().Start()
}
func CtxFileUpload(ctx *context.Context) string {
file, info, _ := ctx.FormFile("file")
defer func(file multipart.File) {
_ = file.Close()
}(file)
lastFileName := NextId.Generate().String() + "_" + info.Filename
fileName := time.Now().Format("20060102") + "/" + lastFileName
targetPath := "./static/uploads/" + time.Now().Format("20060102")
if _, err := os.Stat(targetPath); os.IsNotExist(err) {
_ = os.MkdirAll(targetPath, os.ModePerm)
}
filePath := "static/uploads/" + fileName
// 创建目标文件
destFilePath := filepath.Join(targetPath, lastFileName)
destFile, _ := os.Create(destFilePath)
defer func(destFile *os.File) {
_ = destFile.Close()
}(destFile)
// 将上传的文件内容复制到目标文件中
id, _ := io.Copy(destFile, file)
zap_server.ZAPLOG.Info("CtxFileUpload : ", zap.Any("filePath", filePath), zap.Any("id", id))
return fileName
}