1 Star 0 Fork 0

fkil555/gin-extend

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
app_version.go 2.32 KB
一键复制 编辑 原始数据 按行查看 历史
fkil555 提交于 2023-09-10 21:31 . gin-extend init
package app_version
import (
"errors"
"strconv"
"strings"
)
const (
VERSION_EQUAL = 0
VERSION_GREATER_THAN = 1
VERSION_LESS_THAN = 2
)
// 客户端版本比较
func VersionCompare(v1, v2, operator string) (ok bool, err error) {
ok = false
var result int
if result, err = compare(v1, v2); err != nil {
return
}
switch operator {
case "==":
if result == VERSION_EQUAL {
ok = true
}
case "<":
if result == VERSION_LESS_THAN {
ok = true
}
case ">":
if result == VERSION_GREATER_THAN {
ok = true
}
case "<=":
if result == VERSION_EQUAL || result == VERSION_LESS_THAN {
ok = true
}
case ">=":
if result == VERSION_EQUAL || result == VERSION_GREATER_THAN{
ok = true
}
default:
err = errors.New("非法比较符")
ok = false
}
return
}
// 替换版本号中的无效字符
var replaceMap = map[string]string{"V": "", "v": "", "-": "."}
func preprocessVersion(ver string) (intVerList []int, err error) {
for raw, replace := range replaceMap {
//if strings.Contains(ver, raw) {
ver = strings.Replace(ver, raw, replace, -1)
//}
}
strVerList := strings.Split(ver, ".")
intVerList = make([]int, 0)
for _, strVer := range strVerList {
var intVer int
strVer = strings.TrimSpace(strVer)
if intVer, err = strconv.Atoi(strVer); err != nil {
return
}
intVerList = append(intVerList, intVer)
}
return
}
func compare(v1, v2 string) (result int, err error) {
var ver1, ver2 []int
if ver1, err = preprocessVersion(v1); err != nil {
return
}
if ver2, err = preprocessVersion(v2); err != nil {
return
}
minLen := len(ver1)
if len(ver2) < minLen {
minLen = len(ver2)
}
for i := 0; i < minLen; i++ {
if ver1[i] < ver2[i] {
return VERSION_LESS_THAN, nil
} else if ver1[i] > ver2[i] {
return VERSION_GREATER_THAN, nil
}
}
if len(ver1) < len(ver2) {
result = VERSION_LESS_THAN
} else if len(ver1) > len(ver2) {
result = VERSION_GREATER_THAN
} else {
result = VERSION_EQUAL
}
return
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/fkil555/gin-extend.git
git@gitee.com:fkil555/gin-extend.git
fkil555
gin-extend
gin-extend
v0.0.5

搜索帮助