125 lines
2.5 KiB
Go
125 lines
2.5 KiB
Go
package version
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"fonchain-fiee/pkg/cache"
|
|
"fonchain-fiee/pkg/model/query"
|
|
"fonchain-fiee/pkg/model/vo"
|
|
"fonchain-fiee/pkg/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gin-gonic/gin/binding"
|
|
"github.com/go-redis/redis"
|
|
)
|
|
|
|
// handlePanic 统一处理 panic 恢复
|
|
func handlePanic(c *gin.Context) {
|
|
if r := recover(); r != nil {
|
|
var err error
|
|
switch v := r.(type) {
|
|
case error:
|
|
err = v
|
|
case string:
|
|
err = fmt.Errorf("panic: %s", v)
|
|
default:
|
|
err = fmt.Errorf("panic: %v", v)
|
|
}
|
|
service.Error(c, err)
|
|
}
|
|
}
|
|
|
|
// containsVersion 检查版本是否存在于版本列表中
|
|
func containsVersion(versions []string, targetVersion string) bool {
|
|
for _, version := range versions {
|
|
if version == targetVersion {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func Version(c *gin.Context) {
|
|
var req query.VersionQuery
|
|
|
|
if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
|
|
service.Error(c, err)
|
|
return
|
|
}
|
|
|
|
val, _ := cache.RedisClient.Get("app:version:" + req.AppName).Result()
|
|
if val == "" {
|
|
val = "1.0.0"
|
|
cache.RedisClient.Set("app:version:"+req.AppName, val, 0)
|
|
}
|
|
|
|
service.Success(c, vo.VersionVo{Version: val})
|
|
}
|
|
|
|
func StoreBrandsVersions(c *gin.Context) {
|
|
defer handlePanic(c)
|
|
|
|
var brands []struct {
|
|
Brand string `json:"brand"`
|
|
Version []string `json:"version"`
|
|
}
|
|
|
|
if err := c.ShouldBindBodyWith(&brands, binding.JSON); err != nil {
|
|
service.Error(c, err)
|
|
return
|
|
}
|
|
|
|
for _, brand := range brands {
|
|
versionData, err := json.Marshal(brand.Version)
|
|
if err != nil {
|
|
service.Error(c, err)
|
|
return
|
|
}
|
|
|
|
if err = cache.RedisClient.HSet("brands_versions", brand.Brand, versionData).Err(); err != nil {
|
|
service.Error(c, err)
|
|
return
|
|
}
|
|
}
|
|
|
|
service.Success(c, true)
|
|
}
|
|
|
|
func CheckBrandVersion(c *gin.Context) {
|
|
defer handlePanic(c)
|
|
|
|
var brand struct {
|
|
Brand string `json:"brand"`
|
|
Version string `json:"version"`
|
|
}
|
|
|
|
if err := c.ShouldBindBodyWith(&brand, binding.JSON); err != nil {
|
|
service.Error(c, err)
|
|
return
|
|
}
|
|
|
|
storedVersionsStr, err := cache.RedisClient.HGet("brands_versions", brand.Brand).Result()
|
|
|
|
// 品牌不存在,返回 false
|
|
if errors.Is(err, redis.Nil) {
|
|
service.Success(c, false)
|
|
return
|
|
}
|
|
|
|
if err != nil {
|
|
service.Error(c, err)
|
|
return
|
|
}
|
|
|
|
var storedVersions []string
|
|
if err = json.Unmarshal([]byte(storedVersionsStr), &storedVersions); err != nil {
|
|
service.Error(c, err)
|
|
return
|
|
}
|
|
|
|
// 检查版本是否存在
|
|
versionFound := containsVersion(storedVersions, brand.Version)
|
|
service.Success(c, versionFound)
|
|
}
|