Compare commits

..

3 Commits

Author SHA1 Message Date
f8f647c12a update 2026-02-22 14:31:06 +08:00
d88178458d 更新 README.md 2025-12-25 21:26:34 +08:00
9b570c04c0 fix licence logic 2025-12-25 20:35:07 +08:00
14 changed files with 558 additions and 552 deletions

View File

@@ -11,6 +11,16 @@ go env -w GOINSECURE=git.apinb.com/*
go env -w GONOSUMDB=git.apinb.com/*
```
### 配置环境变量
```bash
export BSM_Workspace=def
export BSM_JwtSecretKey=your_secret_key
export BSM_RuntimeMode=dev
export BSM_Prefix=/usr/local/bsm
```
## 核心功能模块
### 1. 服务管理 (service)
@@ -321,14 +331,6 @@ go env -w GONOSUMDB=git.apinb.com/*
- 支持许可证文件验证
### 配置环境变量
```bash
export BSM_Workspace=def
export BSM_JwtSecretKey=your_secret_key
export BSM_RuntimeMode=dev
export BSM_Prefix=/usr/local/bsm
```
### 安全建议

14
cache/redis/cache.go vendored
View File

@@ -5,6 +5,7 @@ package redis
import (
"encoding/json"
"fmt"
"strings"
"time"
"git.apinb.com/bsm-sdk/core/errcode"
@@ -15,19 +16,20 @@ import (
// prefix: 键前缀
// params: 键参数
// 返回: 完整的缓存键
func (c *RedisClient) BuildKey(prefix string, params ...interface{}) string {
key := vars.CacheKeyPrefix + prefix
func (c *RedisClient) BuildKey(prefix string, params ...any) string {
var key strings.Builder
key.WriteString(vars.CacheKeyPrefix + prefix)
for _, param := range params {
key += fmt.Sprintf(":%v", param)
key.WriteString(fmt.Sprintf(":%v", param))
}
return key
return key.String()
}
// Get 获取缓存
// key: 缓存键
// result: 存储结果的指针
// 返回: 错误信息
func (c *RedisClient) Get(key string, result interface{}) error {
func (c *RedisClient) Get(key string, result any) error {
if c.Client == nil {
return errcode.ErrRedis
}
@@ -45,7 +47,7 @@ func (c *RedisClient) Get(key string, result interface{}) error {
// value: 缓存值
// ttl: 过期时间
// 返回: 错误信息
func (c *RedisClient) Set(key string, value interface{}, ttl time.Duration) error {
func (c *RedisClient) Set(key string, value any, ttl time.Duration) error {
if c.Client == nil {
return errcode.ErrRedis
}

View File

@@ -62,7 +62,7 @@ func (t *tokenJwt) GenerateJwt(id uint, identity, client, role string, owner any
// 解析JWT
func (t *tokenJwt) ParseJwt(tokenstring string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenstring, &Claims{}, func(token *jwt.Token) (interface{}, error) {
token, err := jwt.ParseWithClaims(tokenstring, &Claims{}, func(token *jwt.Token) (any, error) {
return []byte(t.SecretKey), nil
})
if claims, ok := token.Claims.(*Claims); ok && token.Valid {

View File

@@ -44,7 +44,7 @@ func NewElastic(endpoints []string, username, password string) (*ES, error) {
// "time": time.Now().Unix(),
// "date": time.Now(),
// }
func (es *ES) CreateDocument(index string, id string, doc *interface{}) {
func (es *ES) CreateDocument(index string, id string, doc *any) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(doc); err != nil {
log.Println("Elastic NewEncoder:", err)
@@ -75,7 +75,7 @@ func (es *ES) CreateDocument(index string, id string, doc *interface{}) {
// index 如果文档不存在就创建,如果文档存在就更新
// update 更新一个文档,如果文档不存在就返回错误
// delete 删除一个文档如果要删除的文档id不存在就返回错误
func (es *ES) Batch(index string, documens []map[string]interface{}, action string) {
func (es *ES) Batch(index string, documens []map[string]any, action string) {
log.SetFlags(0)
var (
@@ -162,7 +162,7 @@ func (es *ES) Batch(index string, documens []map[string]interface{}, action stri
}
}
func (es *ES) Search(index string, query map[string]interface{}) (res *esapi.Response, err error) {
func (es *ES) Search(index string, query map[string]any) (res *esapi.Response, err error) {
var buf bytes.Buffer
if err = json.NewEncoder(&buf).Encode(query); err != nil {
return
@@ -201,7 +201,7 @@ func (es *ES) Delete(index, idx string) (res *esapi.Response, err error) {
return
}
func (es *ES) DeleteByQuery(index []string, query map[string]interface{}) (res *esapi.Response, err error) {
func (es *ES) DeleteByQuery(index []string, query map[string]any) (res *esapi.Response, err error) {
var buf bytes.Buffer
if err = json.NewEncoder(&buf).Encode(query); err != nil {
return

2
go.mod
View File

@@ -1,3 +1,3 @@
module git.apinb.com/bsm-sdk/core
go 1.25.1
go 1.26.0

View File

@@ -14,6 +14,7 @@ import (
"os"
"path"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
@@ -47,38 +48,50 @@ type Licence struct {
CreateDate int `json:"create"` // 生效日期
ExpireDate int `json:"expire"` // 有效期
MachineCodes []string `json:"machine_codes"` // 机器码列表
Args map[string]string `json:"args"` // 许可证相关参数定义
}
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var (
des_key string
des_iv string
args map[string]string
Check_Licence_File bool = true // 是否检查部署授权文件
)
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
const (
signKey = "1F36659EC27CFFF849E068EA80B1A4CA"
LICENCE_KEY = "BLOCKS_KEY"
SignKey = "1F36659EC27CFFF849E068EA80B1A4CA"
LicenceKey = "BLOCKS_KEY"
)
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func init() {
des_key = base64.StdEncoding.EncodeToString([]byte(signKey))
des_iv = base64.StdEncoding.EncodeToString([]byte(signKey[:16]))
des_key = base64.StdEncoding.EncodeToString([]byte(SignKey))
des_iv = base64.StdEncoding.EncodeToString([]byte(SignKey[:16]))
}
func WatchCheckLicence(licPath, licName string) {
utils.SetInterval(func() {
if !CheckLicence(licPath, licName) {
log.Println("授权文件失效,请重新部署授权文件:", licPath)
os.Exit(99)
exit()
}
}, time.Hour*1)
}
func GetArgs(licPath, licName string) map[string]string {
if !CheckLicence(licPath, licName) {
exit()
}
return args
}
func exit() {
log.Println("授权文件失效,请重新部署授权文件!")
os.Exit(99)
}
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
func CheckLicence(licPath, licName string) bool {
// 加载授权文件
@@ -97,6 +110,8 @@ func CheckLicence(licPath, licName string) bool {
return false
}
args = l.Args
return l.VerifyLicence(licName)
}
@@ -121,13 +136,7 @@ func (l *Licence) VerifyLicence(licName string) bool {
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// 检查机器码是否存在授权列表中
func (l *Licence) ValidMachineCode(code string) bool {
result := false
for _, c := range l.MachineCodes {
if c == code {
result = true
break
}
}
result := slices.Contains(l.MachineCodes, code)
return result
}
@@ -195,13 +204,14 @@ func EncryptStr(txt string) string {
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// 生成授权文件
func BuildLicence(company_name string, Create_date int, expire_date int, machine_codes []string) (string, error) {
func BuildLicence(company_name string, Create_date int, expire_date int, machine_codes []string, args map[string]string) (string, error) {
// 构造licence
licence := &Licence{
CompanyName: company_name,
CreateDate: Create_date,
ExpireDate: expire_date,
MachineCodes: machine_codes,
Args: args,
}
content, err := json.Marshal(licence)
@@ -216,7 +226,7 @@ func BuildLicence(company_name string, Create_date int, expire_date int, machine
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// 生成激活码
func GetLicenceCode(machinceCode string) string {
return hash256(machinceCode + "&" + signKey)
return hash256(machinceCode + "&" + SignKey)
}
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -250,7 +260,7 @@ func getMacAddrs() []string {
if err != nil {
return macs
}
for i := 0; i < len(netfaces); i++ {
for i := range netfaces {
if (netfaces[i].Flags&net.FlagUp) != 0 && (netfaces[i].Flags&net.FlagLoopback) == 0 {
addrs, _ := netfaces[i].Addrs()
for _, address := range addrs {

View File

@@ -159,7 +159,7 @@ func (l *Logger) sendToRemote(level, name, out string) {
if l.endpoint == "" {
return
}
data := map[string]interface{}{
data := map[string]any{
"level": level,
"name": name,
"out": out,
@@ -169,7 +169,7 @@ func (l *Logger) sendToRemote(level, name, out string) {
}
// Debug 输出调试信息
func (l *Logger) Debug(v ...interface{}) {
func (l *Logger) Debug(v ...any) {
if l.level <= vars.DEBUG {
l.checkAndRotateLog()
out := fmt.Sprint(v...)
@@ -181,7 +181,7 @@ func (l *Logger) Debug(v ...interface{}) {
}
// Debugf 格式化输出调试信息
func (l *Logger) Debugf(format string, v ...interface{}) {
func (l *Logger) Debugf(format string, v ...any) {
if l.level <= vars.DEBUG {
l.checkAndRotateLog()
out := fmt.Sprintf(format, v...)
@@ -193,7 +193,7 @@ func (l *Logger) Debugf(format string, v ...interface{}) {
}
// Info 输出信息
func (l *Logger) Info(v ...interface{}) {
func (l *Logger) Info(v ...any) {
if l.level <= vars.INFO {
l.checkAndRotateLog()
out := fmt.Sprint(v...)
@@ -205,7 +205,7 @@ func (l *Logger) Info(v ...interface{}) {
}
// Infof 格式化输出信息
func (l *Logger) Infof(format string, v ...interface{}) {
func (l *Logger) Infof(format string, v ...any) {
if l.level <= vars.INFO {
l.checkAndRotateLog()
out := fmt.Sprintf(format, v...)
@@ -217,7 +217,7 @@ func (l *Logger) Infof(format string, v ...interface{}) {
}
// Warn 输出警告
func (l *Logger) Warn(v ...interface{}) {
func (l *Logger) Warn(v ...any) {
if l.level <= vars.WARN {
l.checkAndRotateLog()
out := fmt.Sprint(v...)
@@ -229,7 +229,7 @@ func (l *Logger) Warn(v ...interface{}) {
}
// Warnf 格式化输出警告
func (l *Logger) Warnf(format string, v ...interface{}) {
func (l *Logger) Warnf(format string, v ...any) {
if l.level <= vars.WARN {
l.checkAndRotateLog()
out := fmt.Sprintf(format, v...)
@@ -241,7 +241,7 @@ func (l *Logger) Warnf(format string, v ...interface{}) {
}
// Error 输出错误
func (l *Logger) Error(v ...interface{}) {
func (l *Logger) Error(v ...any) {
if l.level <= vars.ERROR {
l.checkAndRotateLog()
out := fmt.Sprint(v...)
@@ -253,7 +253,7 @@ func (l *Logger) Error(v ...interface{}) {
}
// Errorf 格式化输出错误
func (l *Logger) Errorf(format string, v ...interface{}) {
func (l *Logger) Errorf(format string, v ...any) {
if l.level <= vars.ERROR {
l.checkAndRotateLog()
out := fmt.Sprintf(format, v...)
@@ -265,7 +265,7 @@ func (l *Logger) Errorf(format string, v ...interface{}) {
}
// Fatal 输出致命错误并退出程序
func (l *Logger) Fatal(v ...interface{}) {
func (l *Logger) Fatal(v ...any) {
l.checkAndRotateLog()
out := fmt.Sprint(v...)
if l.onRemote {
@@ -276,7 +276,7 @@ func (l *Logger) Fatal(v ...interface{}) {
}
// Fatalf 格式化输出致命错误并退出程序
func (l *Logger) Fatalf(format string, v ...interface{}) {
func (l *Logger) Fatalf(format string, v ...any) {
l.checkAndRotateLog()
out := fmt.Sprintf(format, v...)
if l.onRemote {
@@ -287,17 +287,17 @@ func (l *Logger) Fatalf(format string, v ...interface{}) {
}
// Print 输出信息兼容标准log包
func (l *Logger) Print(v ...interface{}) {
func (l *Logger) Print(v ...any) {
l.Info(v...)
}
// Printf 格式化输出信息兼容标准log包
func (l *Logger) Printf(format string, v ...interface{}) {
func (l *Logger) Printf(format string, v ...any) {
l.Infof(format, v...)
}
// Println 输出信息并换行兼容标准log包
func (l *Logger) Println(v ...interface{}) {
func (l *Logger) Println(v ...any) {
l.Info(v...)
}
@@ -326,91 +326,91 @@ func (l *Logger) Close() error {
// 全局日志函数兼容标准log包
// Debug 全局调试日志
func Debug(v ...interface{}) {
func Debug(v ...any) {
if globalLogger != nil {
globalLogger.Debug(v...)
}
}
// Debugf 全局调试日志
func Debugf(format string, v ...interface{}) {
func Debugf(format string, v ...any) {
if globalLogger != nil {
globalLogger.Debugf(format, v...)
}
}
// Info 全局信息日志
func Info(v ...interface{}) {
func Info(v ...any) {
if globalLogger != nil {
globalLogger.Info(v...)
}
}
// Infof 全局信息日志
func Infof(format string, v ...interface{}) {
func Infof(format string, v ...any) {
if globalLogger != nil {
globalLogger.Infof(format, v...)
}
}
// Warn 全局警告日志
func Warn(v ...interface{}) {
func Warn(v ...any) {
if globalLogger != nil {
globalLogger.Warn(v...)
}
}
// Warnf 全局警告日志
func Warnf(format string, v ...interface{}) {
func Warnf(format string, v ...any) {
if globalLogger != nil {
globalLogger.Warnf(format, v...)
}
}
// Error 全局错误日志
func Error(v ...interface{}) {
func Error(v ...any) {
if globalLogger != nil {
globalLogger.Error(v...)
}
}
// Errorf 全局错误日志
func Errorf(format string, v ...interface{}) {
func Errorf(format string, v ...any) {
if globalLogger != nil {
globalLogger.Errorf(format, v...)
}
}
// Fatal 全局致命错误日志
func Fatal(v ...interface{}) {
func Fatal(v ...any) {
if globalLogger != nil {
globalLogger.Fatal(v...)
}
}
// Fatalf 全局致命错误日志
func Fatalf(format string, v ...interface{}) {
func Fatalf(format string, v ...any) {
if globalLogger != nil {
globalLogger.Fatalf(format, v...)
}
}
// Print 全局打印日志兼容标准log包
func Print(v ...interface{}) {
func Print(v ...any) {
if globalLogger != nil {
globalLogger.Print(v...)
}
}
// Printf 全局打印日志兼容标准log包
func Printf(format string, v ...interface{}) {
func Printf(format string, v ...any) {
if globalLogger != nil {
globalLogger.Printf(format, v...)
}
}
// Println 全局打印日志兼容标准log包
func Println(v ...interface{}) {
func Println(v ...any) {
if globalLogger != nil {
globalLogger.Println(v...)
}

View File

@@ -16,25 +16,25 @@ func init() {
}
// record INFO message. Color White
func Info(format string, a ...interface{}) {
func Info(format string, a ...any) {
message := fmt.Sprintf("\033[37m[Info] "+format+"\033[0m\n", a...)
logger.Print(message)
}
// record Warn message. Color Orange
func Warn(format string, a ...interface{}) {
func Warn(format string, a ...any) {
message := fmt.Sprintf("\033[33m[Warn] "+format+"\033[0m\n", a...)
logger.Print(message)
}
// record Success message. Color Green
func Success(format string, a ...interface{}) {
func Success(format string, a ...any) {
message := fmt.Sprintf("\033[32m[Succ] "+format+"\033[0m\n", a...)
logger.Print(message)
}
// record ERROR message. Color Red
func Error(format string, a ...interface{}) {
func Error(format string, a ...any) {
message := fmt.Sprintf("\033[31m[Error] "+format+"\033[0m\n", a...)
logger.Print(message)
}

View File

@@ -56,7 +56,7 @@ func WeChat_Pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
if n == 0 || n > len(data) {
return nil, ErrInvalidPKCS7Padding
}
for i := 0; i < n; i++ {
for i := range n {
if data[len(data)-n+i] != c {
return nil, ErrInvalidPKCS7Padding
}

View File

@@ -1,5 +1,7 @@
package utils
import "slices"
import "strings"
// ArrayInString 判断字符串是否存在于字符串切片中
@@ -7,24 +9,14 @@ import "strings"
// array: 需要查找的字符串切片
func ArrayInString(target string, array []string) bool {
target = strings.TrimSpace(target)
for _, v := range array {
if strings.TrimSpace(v) == target {
return true
}
}
return false
return slices.Contains(array, target)
}
// ArrayInInt 判断整数是否存在于整型切片中
// target: 待匹配的目标整数
// array: 需要查找的整型切片
func ArrayInInt(target int, array []int) bool {
for _, v := range array {
if v == target {
return true
}
}
return false
return slices.Contains(array, target)
}
// ArrayRemoveRepeatString 去除字符串切片中的重复元素(保持原有顺序)

View File

@@ -103,7 +103,7 @@ func BinaryToDecimal(bit string) (num int) {
fields := strings.Split(bit, "")
lens := len(fields)
var tempF float64 = 0
for i := 0; i < lens; i++ {
for i := range lens {
floatNum := String2Float64(fields[i])
tempF += floatNum * math.Pow(2, float64(lens-i-1))
}

View File

@@ -5,7 +5,7 @@ import (
"strings"
)
func If(condition bool, trueValue, falseValue interface{}) interface{} {
func If(condition bool, trueValue, falseValue any) any {
if condition {
return trueValue
}
@@ -21,8 +21,8 @@ func FirstToUpper(str string) string {
return strings.ToUpper(str[:1]) + strings.ToLower(str[1:])
}
func ParseParams(in map[string]string) map[string]interface{} {
out := make(map[string]interface{})
func ParseParams(in map[string]string) map[string]any {
out := make(map[string]any)
for k, v := range in {
fv, err := strconv.ParseFloat(v, 64)
if err != nil {

View File

@@ -341,8 +341,8 @@ func GenerateQRCodeWithLogo(content, logoPath string, size ...int) ([]byte, erro
// 绘制Logo
logoOriginalBounds := logoImage.Bounds()
for y := 0; y < logoSize; y++ {
for x := 0; x < logoSize; x++ {
for y := range logoSize {
for x := range logoSize {
// 计算原始Logo的对应像素
origX := x * logoOriginalBounds.Dx() / logoSize
origY := y * logoOriginalBounds.Dy() / logoSize

View File

@@ -9,7 +9,7 @@ func RandomString(l int) string {
str := "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
bytes := []byte(str)
var result []byte = make([]byte, 0, l)
for i := 0; i < l; i++ {
for range l {
result = append(result, bytes[rand.IntN(len(bytes))])
}
return string(result)
@@ -20,7 +20,7 @@ func RandomPureString(l int) string {
str := "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
bytes := []byte(str)
var result []byte = make([]byte, 0, l)
for i := 0; i < l; i++ {
for range l {
result = append(result, bytes[rand.IntN(len(bytes))])
}
return string(result)
@@ -31,7 +31,7 @@ func RandomPureUpString(l int) string {
str := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
var result []byte = make([]byte, 0, l)
for i := 0; i < l; i++ {
for range l {
result = append(result, bytes[rand.IntN(len(bytes))])
}
return string(result)
@@ -42,7 +42,7 @@ func RandomNumber(l int) string {
str := "0123456789"
bytes := []byte(str)
var result []byte
for i := 0; i < l; i++ {
for range l {
result = append(result, bytes[rand.IntN(len(bytes))])
}
return string(result)