Compare commits

..

79 Commits

Author SHA1 Message Date
f2d8ae26f6 build(go): 移除 go.mod 中所有依赖项声明
清理 go.mod 文件,移除了所有直接和间接的依赖项引用,
可能为后续依赖管理或模块重构做准备。
2025-09-22 19:03:20 +08:00
dbf68c38c1 ```
docs(readme): 重构 README 文档结构并补充模块说明

- 重新组织 README 内容,明确划分私有仓库设置、功能模块等章节
- 补充 crypto、cache、database、middleware、queue 和 utils 模块的功能简介
- 统一代码示例格式,增加 bash 和 go 语言标识

feat(crypto): 优化 PKCS7 填充与去填充函数实现

- 新增 PKCS7Padding 和 PKCS7UnPadding 函数的详细注释
- 添加对输入参数的有效性校验,提升健壮性
- 修复可能引发越界 panic 的潜在问题

feat(database): 完善数据库连接及初始化逻辑

- 为 NewDatabase、NewMysql 和 NewPostgres 函数添加完整注释
- 修复 MaxOpenConns 配置未正确赋值的问题
- 在获取 *sql.DB 实例时增加错误处理逻辑
- 支持通过 Init 变量在连接建立后执行自定义初始化函数

feat(go.mod): 初始化项目依赖管理并引入核心组件

- 添加项目所需的主要依赖包,包括 gin、gorm、redis、nats 等
- 引入常用的工具库如 uuid、ulid、gopsutil 等
- 自动拉取并锁定所有间接依赖版本
```
2025-09-22 19:02:38 +08:00
f70f8d94db fix(with): 修复 memory.go 中的配置初始化错误
将 bigcache.Config 结构体实例改为指针传递,确保配置能够正确初始化和传递。
2025-09-20 11:32:24 +08:00
257f0a6b6e fix(with): 优化 memory cache 配置初始化逻辑
移除未使用的 `encoding/json` 包导入。
调整配置初始化方式,避免不必要的结构体拷贝。
改进日志输出内容,仅显示关键配置项。
2025-09-20 11:21:02 +08:00
5e25e8eccc fix(with/etcd): 修改Etcd配置为空时的处理逻辑
当Etcd配置或端点为空时,将panic改为直接返回,避免程序崩溃
2025-09-20 11:08:47 +08:00
4f584726d6 ```
refactor(with): 调整Memory函数参数顺序

将Memory函数的参数顺序从(opts, cli)调整为(cli, opts),
使函数签名更加符合常规的客户端优先参数排列习惯,
提升代码可读性和一致性。
```
2025-09-20 10:59:45 +08:00
b9d144353e ```
refactor(cache): 移除内存缓存和Redis缓存的初始化逻辑

移除了mem包中内存缓存的初始化函数,以及with包中Redis缓存的初始化函数。
这些缓存初始化逻辑将被重构到其他位置或采用新的实现方式。
```
2025-09-20 10:55:06 +08:00
7e7fa16441 ```
feat(database): 新增数据库初始化函数

新增 NewDatabase 函数,支持根据驱动类型初始化 MySQL 或 Postgres 数据库连接。
该函数根据传入的驱动名称自动路由到对应的数据库连接创建逻辑,并提供错误处理。
```
2025-09-20 10:30:06 +08:00
bc2cb53287 database 新增 new,MigrateTables 2025-09-18 13:56:58 +08:00
cef8b55fba feat(conf/new.go): 添加配置文件不存在时的处理逻辑及环境变量替换
在`New`函数中增加了对配置文件不存在时的处理逻辑,如果指定的服务配置文件不存在,则尝试读取基于工作空间的配置文件。此外,在加载YAML配置之前,新增了对环境变量的替换步骤,确保配置中的环境变量能够被正确解析。

这些改动提高了配置加载过程的灵活性与适应性,使得应用能够在缺少特定服务配置的情况下也能正常启动,并且支持通过环境变量动态调整配置内容。
2025-09-18 13:34:35 +08:00
2e07861622 build: 更新 go.mod 文件
- 移除了大量未使用的依赖包
- 保留了必要的依赖包
- 优化了项目结构,提高了代码的可维护性
2025-09-12 23:28:07 +08:00
e30d50845a feat(vars): 添加 OK 状态码
在 status.go 文件中添加了新的状态码 OK,值为 "OK"。这个状态码可以用于表示系统或组件运行正常的情况。
2025-09-12 23:27:14 +08:00
b4cd51a6dc refactor(encipher): 更新 JWT 过期时间变量
- 将 vars.JwtExpireDay 更改为 vars.JwtExpire,使代码更具通用性
- 优化了 GenerateTokenAes 函数中的过期时间计算逻辑
2025-09-12 20:11:49 +08:00
dac969d798 refactor(vars): 修改 JWT 过期时间变量名称
- 将 JwtExpireDay 重命名为 JwtExpire
- 新变量名称更加简洁,同时消除了冗余的 Day 后缀
2025-09-12 18:56:23 +08:00
2f398c73b3 add middleware for CORS and mode configuration 2025-09-02 10:01:09 +08:00
zhaoxiaorong
cb8e9bad4b fix 操作痕迹可选加密 2025-09-01 12:40:23 +08:00
zhaoxiaorong
1005e89e4f Merge branch 'main' of https://git.apinb.com/bsm-sdk/core 2025-08-23 21:17:56 +08:00
zhaoxiaorong
268c7f99c7 fix 取消从redis获取token,改为从token中获取有效时间 2025-08-23 21:17:51 +08:00
fc72fd123d add PrintJson 2025-08-22 12:15:55 +08:00
63a4653eb2 add CopyFile 2025-08-21 10:59:18 +08:00
ffb706df32 Merge branch 'main' of https://git.apinb.com/bsm-sdk/core 2025-08-11 14:42:38 +08:00
282cdde7f9 add file free by filter and allow 2025-08-11 14:42:23 +08:00
zhaoxiaorong
e28934d7b8 fix 2025-07-29 09:48:53 +08:00
zhaoxiaorong
93491fa747 fix 2025-07-29 09:43:14 +08:00
zhaoxiaorong
f8d7737723 fix 2025-07-25 15:10:59 +08:00
zhaoxiaorong
35104ebb90 fix 2025-07-04 16:03:47 +08:00
fc7c1e87a6 fix licence watch 2025-05-28 15:58:28 +08:00
zhaoxiaorong
8c62f529e3 Merge branch 'main' of https://git.apinb.com/bsm-sdk/core 2025-05-27 09:41:00 +08:00
zhaoxiaorong
9d3b3404e4 fix 2025-05-27 09:40:56 +08:00
bfccf4d468 fix licence 2025-05-26 22:11:47 +08:00
cd72620e49 add HttpPostJSON 2025-05-23 10:45:28 +08:00
zhaoxiaorong
5bb23deb3b fix 2025-05-21 20:13:55 +08:00
2c713adc16 add sync map data. 2025-05-03 15:49:16 +08:00
zhaoxiaorong
21f09ea41e fix 2025-04-24 17:52:29 +08:00
4d06ad3e8b add err code 2025-04-19 20:14:37 +08:00
52a81a404e fix infra response 2025-04-18 19:11:50 +08:00
6cd06d86bc add std_owner 2025-04-17 17:18:58 +08:00
zhaoxiaorong
ca9f7047c6 fix 兼容性调整 2025-04-15 21:49:17 +08:00
zhaoxiaorong
2de73fea00 fix 兼容性调整 2025-04-15 20:50:28 +08:00
zhaoxiaorong
4b73f086b1 dev oplog 2025-04-11 18:14:07 +08:00
zhaoxiaorong
c08950c10a fix 2025-04-11 18:06:08 +08:00
zhaoxiaorong
d691648916 fix 2025-04-11 17:53:50 +08:00
zhaoxiaorong
8060cdb508 fix 2025-04-11 17:50:06 +08:00
zhaoxiaorong
50c23df124 fix 2025-04-11 17:44:49 +08:00
zhaoxiaorong
04b8e5b03b fix 2025-04-11 16:45:11 +08:00
zhaoxiaorong
dd95b8d8b1 fix 2025-04-09 15:24:28 +08:00
zhaoxiaorong
dd9a692858 fix 2025-04-09 11:12:42 +08:00
zhaoxiaorong
b5374b85ff fix 2025-04-09 10:56:49 +08:00
zhaoxiaorong
5172824358 fix 2025-04-09 10:34:01 +08:00
zhaoxiaorong
51ff7d1ffd fix 2025-04-09 10:19:15 +08:00
zhaoxiaorong
c7f24e3b6d fix 2025-04-09 09:39:51 +08:00
f7948263c5 Merge branch 'main' of https://git.apinb.com/bsm-sdk/core 2025-04-08 15:20:34 +08:00
fc42bc92ff fix parse meta ctx 2025-04-08 15:20:22 +08:00
b8f693ef82 fix net getLocationIP 2025-04-07 11:14:07 +08:00
6ec06c2813 add third 2025-04-06 13:42:44 +08:00
7983651fcd add time <=> string 2025-04-02 14:53:45 +08:00
d7fb72b5e0 add types.db identity default:uuid_generate_v4() 2025-04-01 23:34:24 +08:00
6d1f59fd35 add gateway 2025-03-30 13:24:13 +08:00
93daa022bc add gateway 2025-03-30 13:23:46 +08:00
ca00b34e24 add GatewayConf 2025-03-29 20:14:26 +08:00
922cfd6a02 feat:service mod 2025-03-29 15:02:49 +08:00
d131495f4f up go.mod 2025-03-27 03:17:48 +08:00
04451d4b2f add conf.PrintInfo 2025-03-27 03:10:56 +08:00
e184fff689 add conf.PrintInfo 2025-03-27 03:08:59 +08:00
33d1b2e0ee add SetOptions 2025-03-27 02:52:01 +08:00
433cd1f8bc fix hash key 2025-03-27 02:49:44 +08:00
da87dee55c fix srv key to lower 2025-03-27 02:43:15 +08:00
4fe311b722 add uuid v7 2025-03-12 17:10:04 +08:00
a4c6acf56d status int8=>int64 2025-03-12 17:01:46 +08:00
ce98b833ae fix print module 2025-02-21 15:11:34 +08:00
4aa5110726 fix log 2025-02-21 14:37:01 +08:00
d4b7e7e9e6 Merge branch 'main' of https://git.apinb.com/bsm-sdk/core 2025-02-20 17:41:21 +08:00
98ee26f215 fix conf 2025-02-20 17:41:11 +08:00
0218dfd02e fix conf 2025-02-20 17:41:08 +08:00
zhaoxiaorong
629ec74be6 response fix 2025-02-20 15:58:54 +08:00
a128eb8461 add err code 2025-02-20 12:35:33 +08:00
c2858f1002 update go.mod 2025-02-18 23:42:23 +08:00
zhaoxiaorong
5819a8e08f fix JwtClaims SsoToken 2025-02-13 18:01:24 +08:00
zhaoxiaorong
a2e3bfab77 fix 2025-02-11 14:22:14 +08:00
43 changed files with 1453 additions and 421 deletions

View File

@@ -1,7 +1,59 @@
# 私有仓库core 设置
# BSM-SDK Core
BSM-SDK Core 是一个企业级后端开发工具包的核心模块,提供了加密解密、配置管理、缓存、数据库访问、中间件等基础功能。
## 私有仓库设置
```bash
go env -w GOPRIVATE=git.apinb.com/*
go env -w GONOPROXY=git.apinb.com/*
go env -w GOINSECURE=git.apinb.com/*
go env -w GONOSUMDB=git.apinb.com/*
```
go env -w GOPRIVATE=git.apinb.com/*
go env -w GONOPROXY=git.apinb.com/*
go env -w GOINSECURE=git.apinb.com/*
go env -w GONOSUMDB=git.apinb.com/*
## 功能模块
### 加密与解密 (crypto)
#### GCM加密
```go
AESGCMEncrypt // GCM 加密
AESGCMDecrypt // GCM 解密
```
#### CBC加密
```go
Encrypt // CBC加密
Decrypt // CBC解密
```
#### ECB加密
```go
AesEncryptECB // ECB加密
AesDecryptECB // ECB解密
```
#### 环境变量检测
```go
AesKeyCheck // 秘钥环境变量检测
```
### 缓存 (cache)
支持 Redis 和内存缓存。
### 数据库 (database)
支持 MySQL 和 PostgreSQL 数据库连接和管理。
### 中间件 (middleware)
提供 CORS、JWT 认证、运行模式控制等中间件功能。
### 消息队列 (queue)
集成 NATS 消息队列。
### 工具类 (utils)
提供 JSON 处理、时间处理、随机数生成等通用工具函数。

14
cache/mem/mem.go vendored
View File

@@ -1,14 +0,0 @@
package mem
import (
"git.apinb.com/bsm-sdk/core/vars"
"github.com/FishGoddess/cachego"
)
func New() cachego.Cache {
return cachego.NewCache(
cachego.WithGC(vars.MemGcDuration),
cachego.WithShardings(vars.MemShardings),
cachego.WithLFU(vars.MemLRUMaxNumber),
)
}

View File

@@ -59,6 +59,6 @@ func New(dsn string, hashRadix string) *RedisClient {
func Hash(s string) int {
h := fnv.New32a()
h.Write([]byte(s))
h.Write([]byte(strings.ToLower(s)))
return int(h.Sum32()) % vars.RedisShardings
}

View File

@@ -12,6 +12,7 @@ import (
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/utils"
"git.apinb.com/bsm-sdk/core/vars"
yaml "gopkg.in/yaml.v3"
)
@@ -26,9 +27,17 @@ func New(srvKey string, cfg any) {
vars.HostName, _ = os.Hostname()
// 构造配置文件路径,输出配置文件信息
cfp := fmt.Sprintf("%s_%s.yaml", srvKey, env.Runtime.Mode)
cfp := fmt.Sprintf("%s_%s.yaml", strings.ToLower(srvKey), env.Runtime.Mode)
cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp)
// 配置文件不存在则读取Workspace配置文件
if !utils.PathExists(cfp) {
cfp = fmt.Sprintf("workspace_%s_%s.yaml", strings.ToLower(env.Runtime.Workspace), env.Runtime.Mode)
cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp)
}
print.Info("[BSM - %s] Config File: %s", srvKey, cfp)
print.Info("[BSM - %s] Check Configure ...", vars.ServiceKey)
// 读取配置文件内容
yamlFile, err := os.ReadFile(cfp)
@@ -36,13 +45,12 @@ func New(srvKey string, cfg any) {
log.Fatalf("ERROR: %v", err)
}
// 检查配置文件中是否存在Service和Port字段
if !strings.Contains(string(yamlFile), "Service:") {
log.Fatalln("ERROR: Service Not Nil", cfp)
}
// 替换环境变量
yamlString := os.ExpandEnv(string(yamlFile))
if !strings.Contains(string(yamlFile), "Port:") {
log.Fatalln("ERROR: Port Not Nil", cfp)
// 检查配置文件中是否存在Service和Port字段
if !strings.Contains(yamlString, "Service:") {
log.Fatalln("ERROR: Service Not Nil", cfp)
}
// 解析YAML
@@ -55,15 +63,29 @@ func New(srvKey string, cfg any) {
func NotNil(values ...string) {
for _, value := range values {
if strings.TrimSpace(value) == "" {
log.Fatalln("ERROR:Must config not nil")
log.Fatalln("ERROR:Must config key not nil")
}
}
}
func CheckPort(port int) int {
if port <= 0 || port >= 65535 {
func PrintInfo(addr string) {
print.Success("[BSM - %s] Config Check Success.", vars.ServiceKey)
print.Info("[BSM - %s] Service Name: %s", vars.ServiceKey, vars.ServiceKey)
print.Info("[BSM - %s] Runtime Mode: %s", vars.ServiceKey, env.Runtime.Mode)
}
func CheckPort(port string) string {
if port == "" {
r := rand.New(rand.NewPCG(1000, uint64(time.Now().UnixNano())))
return r.IntN(65535-1024) + 1024 // 生成1024到65535之间的随机端口
p := r.IntN(65535-1024) + 1024 // 生成1024到65535之间的随机端口
return utils.Int2String(p)
}
return port
}
func CheckIP(ip string) string {
if ip == "" {
return utils.GetLocationIP()
}
return ip
}

View File

@@ -1,11 +1,13 @@
package conf
type Base struct {
Service string `yaml:"Service"` // 服务名称
Port int `yaml:"Port"` // 服务监听端口,0为自动随机端口
Cache string `yaml:"Cache"` // REDIS缓存
OnMicroService bool `yaml:"OnMicroService"` // 是否启用微服务
SecretKey string `yaml:"SecretKey"` // 服务秘钥
Service string `yaml:"Service"` // 服务名称
Port string `yaml:"Port"` // 服务监听端口,0为自动随机端口
Cache string `yaml:"Cache"` // REDIS缓存
SecretKey string `yaml:"SecretKey"` // 服务秘钥
BindIP string `yaml:"BindIP"` // 绑定IP
Addr string `yaml:"Addr"`
OnMicroService bool `yaml:"OnMicroService"`
}
type DBConf struct {
@@ -13,6 +15,16 @@ type DBConf struct {
Source []string `yaml:"Source"` // 数据库连接
}
type MicroServiceConf struct {
Enable bool `yaml:"Enable"` // 是否启用微服务
Anonymous []string `yaml:"Anonymous"`
}
type GatewayConf struct {
Enable bool `yaml:"Enable"` // 是否启用网关服务
Port int `yaml:"Port"` // 服务监听端口
}
type ApmConf struct {
Name string // APM服务名称
Platform string `yaml:"Platform"` // APM平台apm,skywalking
@@ -37,11 +49,14 @@ type RpcConf struct {
}
type OssConf struct {
Platform string `yaml:"Platform"` // oss平台aliyun,tencent,huawei,aws,minio
Site string `yaml:"Site"` // oss站点HOST
Endpoint string `yaml:"Endpoint"` // oss服务接入地址
Region string `yaml:"Region"` // oss服务区域
AccessKeyID string `yaml:"AccessKeyId"` // oss AccessKeyId
AccessKeySecret string `yaml:"AccessKeySecret"` // oss AccessKeySecret
UseSSL bool `yaml:"UseSSL"` // 是否使用SSL
}
type MqConf struct {

View File

@@ -4,10 +4,58 @@ import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
)
// AES加密
// =================== GCM ======================
// AEC GCM 加密
func AESGCMEncrypt(plaintext, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
return hex.EncodeToString(ciphertext), nil
}
// AEC GCM 解密
func AESGCMDecrypt(ciphertext string, key []byte) ([]byte, error) {
data, err := hex.DecodeString(ciphertext)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
return nil, errors.New("密文无效")
}
nonce, cipherbyte := data[:nonceSize], data[nonceSize:]
return gcm.Open(nil, nonce, cipherbyte, nil)
}
// =================== CBC ======================
// AES CBC加密
func Encrypt(key string, iv string, data string) string {
if len(data) == 0 {
return ""
@@ -24,7 +72,7 @@ func Encrypt(key string, iv string, data string) string {
return data
}
// AES解密
// AES CBC解密
func Decrypt(key string, iv string, data string) string {
if len(data) == 0 {
return ""
@@ -102,3 +150,24 @@ func generateKey(key []byte) (genKey []byte) {
}
return genKey
}
func AesKeyCheck(key string) (string, error) {
// 从环境变量获取密钥
keyHex := os.Getenv(key)
if keyHex == "" {
fmt.Println("环境变量 RST_KEY 未设置")
return "", errors.New("环境变量 RST_KEY 未设置")
}
// 解码十六进制字符串的密钥
byteKey, err := hex.DecodeString(keyHex)
if err != nil {
fmt.Printf("密钥解码失败: %v\n", err)
return "", errors.New("密钥解码失败")
}
// 检查密钥长度
if len(byteKey) != 16 && len(key) != 24 && len(key) != 32 {
fmt.Printf("无效的密钥长度: %d 字节 (需要16,24或32字节)\n", len(key))
return "", errors.New("无效的密钥长度,需要16,24或32字节")
}
return keyHex, nil
}

View File

@@ -30,7 +30,7 @@ func GenerateTokenAes(id uint, identity, client, role string, owner any, extend
if !(JwtSecretLen == 16 || JwtSecretLen == 24 || JwtSecretLen == 32) {
return "", errcode.ErrJWTSecretKey
}
expireTime := time.Now().Add(vars.JwtExpireDay)
expireTime := time.Now().Add(vars.JwtExpire)
claims := types.JwtClaims{
ID: id,
Identity: identity,
@@ -104,31 +104,41 @@ func AesDecryptCBC(cryted string) (b []byte, err error) {
return orig, nil
}
// PKCS7Padding 使用PKCS7填充法对明文进行填充
func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
padding := blocksize - len(ciphertext)%blocksize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// 去码
// PKCS7UnPadding 去除PKCS7填充
// bug:runtime error: slice bounds out of range [:-22]
func PKCS7UnPadding(origData []byte, blocksize int) []byte {
// 检查块大小是否有效
if blocksize <= 0 {
return nil
}
// 检查原始数据是否为空
if origData == nil || len(origData) == 0 {
return nil
}
// 检查数据长度是否为块大小的整数倍
if len(origData)%blocksize != 0 {
return nil
}
length := len(origData)
// 获取填充字节数
unpadding := int(origData[length-1])
// 检查去填充后数据长度是否有效
if length-unpadding <= 0 {
return nil
}
// 返回去除填充后的数据
return origData[:(length - unpadding)]
}

58
data/map_float.go Normal file
View File

@@ -0,0 +1,58 @@
package data
import (
"sync"
)
var (
// Cache
CacheMapFloat *MapFloat
)
// lock
type MapFloat struct {
sync.RWMutex
Data map[string]float64
}
func NewMapFloat() *MapFloat {
return &MapFloat{
Data: make(map[string]float64),
}
}
func (c *MapFloat) All() map[string]float64 {
c.RLock()
defer c.RUnlock()
return c.Data
}
func (c *MapFloat) Get(key string) float64 {
c.RLock()
defer c.RUnlock()
vals, ok := c.Data[key]
if !ok {
return 0
}
return vals
}
func (c *MapFloat) Set(key string, val float64) {
c.Lock()
defer c.Unlock()
c.Data[key] = val
}
func (c *MapFloat) Keys() (keys []string) {
c.RLock()
defer c.RUnlock()
for k, _ := range c.Data {
keys = append(keys, k)
}
return
}

51
data/map_string.go Normal file
View File

@@ -0,0 +1,51 @@
package data
import (
"sync"
)
var (
// Cache
CacheMapString *MapString
)
// lock
type MapString struct {
sync.RWMutex
Data map[string]string
}
func NewMapString() *MapString {
return &MapString{
Data: make(map[string]string),
}
}
func (c *MapString) Get(key string) string {
c.RLock()
defer c.RUnlock()
vals, ok := c.Data[key]
if !ok {
return ""
}
return vals
}
func (c *MapString) Set(key, val string) {
c.Lock()
defer c.Unlock()
c.Data[key] = val
}
func (c *MapString) Keys() (keys []string) {
c.RLock()
defer c.RUnlock()
for k, _ := range c.Data {
keys = append(keys, k)
}
return
}

137
database/new.go Normal file
View File

@@ -0,0 +1,137 @@
// Package database provides database connection and management functionality
package database
import (
"fmt"
"strings"
"git.apinb.com/bsm-sdk/core/database/sql"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/vars"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var (
// MigrateTables holds the tables that need to be auto-migrated on database initialization
MigrateTables []any
// Init is an optional initialization function that can be executed after database connection is established
Init *func() = nil
)
// NewDatabase creates a new database connection based on the provided driver type
// It supports both MySQL and PostgreSQL databases
func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *gorm.DB, err error) {
driver = strings.ToLower(driver)
switch driver {
case "mysql":
db, err = NewMysql(dsn, options)
case "postgres":
db, err = NewPostgres(dsn, options)
default:
return nil, fmt.Errorf("unsupported database driver: %s", driver)
}
if err != nil {
return nil, err
}
// Execute the Init function if it's not nil
if Init != nil {
(*Init)()
}
return db, nil
}
// NewMysql creates a MySQL database service
func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
//set connection default val.
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: true,
}
}
gormDb, err = gorm.Open(mysql.Open(dsn[0]), &gorm.Config{
SkipDefaultTransaction: true,
})
if err != nil {
return nil, err
}
if options.Debug {
gormDb = gormDb.Debug()
}
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, err := gormDb.DB()
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(options.MaxOpenConns)
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return gormDb, nil
}
// NewPostgres creates a PostgreSQL database service
func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
//set connection default val.
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: true,
}
}
gormDb, err = sql.NewPostgreSql(dsn[0], options)
if err != nil {
return nil, err
}
if options.Debug {
gormDb = gormDb.Debug()
}
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, err := gormDb.DB()
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(options.MaxOpenConns)
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return
}

View File

@@ -8,6 +8,20 @@ import (
"gorm.io/gorm/schema"
)
func SetOptions(options *types.SqlOptions) *types.SqlOptions {
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: false,
}
}
return options
}
// new grom db.
func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
var err error
@@ -16,7 +30,7 @@ func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
if options == nil {
options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false,
Debug: true,
@@ -42,7 +56,11 @@ func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
}
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, _ := gormDb.DB()
sqlDB, err := gormDb.DB()
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。
@@ -51,4 +69,4 @@ func NewPostgreSql(dsn string, options *types.SqlOptions) (*gorm.DB, error) {
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
return gormDb, nil
}
}

View File

@@ -10,16 +10,23 @@ var (
ErrHeaderRequestId = NewError(101, "Header Request-Id Not Found")
ErrHeaderAuthorization = NewError(102, "Header Authorization Not Found")
ErrHeaderSecretKey = NewError(103, "Header Secret-Key Not Found")
ErrHeaderMustParams = NewError(104, "Header Must Params")
)
// standard error code ,start:110
var (
ErrRequestParse = NewError(111, "Request Parse Fail")
ErrRequestMust = NewError(112, "Request Params Required")
ErrPermission = NewError(113, "Permission Denied")
ErrJsonUnmarshal = NewError(114, "Json Unmarshal Fail")
ErrJsonMarshal = NewError(115, "Json Marshal Fail")
ErrInternal = NewError(116, "Internal Server Error")
ErrEmpty = NewError(110, "Data Is Empty")
ErrRequestParse = NewError(111, "Request Parse Fail")
ErrRequestMust = NewError(112, "Request Params Required")
ErrPermission = NewError(113, "Permission Denied")
ErrJsonUnmarshal = NewError(114, "Json Unmarshal Fail")
ErrJsonMarshal = NewError(115, "Json Marshal Fail")
ErrInternal = NewError(116, "Internal Server Error")
ErrPassword = NewError(117, "Password Incorrect")
ErrAccountNotFound = NewError(118, "Account Not Found")
ErrAccountDisabled = NewError(119, "Account Disabled")
ErrDisabled = NewError(120, "Status Disabled")
ErrRecordNotFound = NewError(121, "Record Not Found")
)
// jwt error code ,start:130

80
go.mod
View File

@@ -1,81 +1,3 @@
module git.apinb.com/bsm-sdk/core
go 1.23.6
require (
github.com/FishGoddess/cachego v0.6.1
github.com/elastic/go-elasticsearch/v8 v8.17.0
github.com/nats-io/nats.go v1.39.0
github.com/oklog/ulid/v2 v2.1.0
github.com/redis/go-redis/v9 v9.7.0
github.com/shirou/gopsutil v3.21.11+incompatible
go.etcd.io/etcd/client/v3 v3.5.18
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/postgres v1.5.11
gorm.io/gorm v1.25.12
)
require (
github.com/bytedance/sonic v1.12.8 // indirect
github.com/bytedance/sonic/loader v0.2.3 // indirect
github.com/cloudwego/base64x v0.1.5 // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gin-contrib/sse v1.0.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.24.0 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.9 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
golang.org/x/arch v0.14.0 // indirect
)
require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/elastic/elastic-transport-go/v8 v8.6.0 // indirect
github.com/gin-gonic/gin v1.10.0
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.7.2 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/nats-io/nkeys v0.4.9 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/tklauser/go-sysconf v0.3.14 // indirect
github.com/tklauser/numcpus v0.9.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.etcd.io/etcd/api/v3 v3.5.18 // indirect
go.etcd.io/etcd/client/pkg/v3 v3.5.18 // indirect
go.opentelemetry.io/otel v1.34.0 // indirect
go.opentelemetry.io/otel/metric v1.34.0 // indirect
go.opentelemetry.io/otel/trace v1.34.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.32.0 // indirect
golang.org/x/net v0.34.0 // indirect
golang.org/x/sync v0.11.0 // indirect
golang.org/x/sys v0.30.0 // indirect
golang.org/x/text v0.22.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250204164813-702378808489 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250204164813-702378808489 // indirect
google.golang.org/grpc v1.70.0
google.golang.org/protobuf v1.36.5 // indirect
)
go 1.24

224
go.sum
View File

@@ -1,224 +0,0 @@
github.com/FishGoddess/cachego v0.6.1 h1:mbytec3loqw5dcO177LyRGyStKG0AngP5g2GR3SzSh0=
github.com/FishGoddess/cachego v0.6.1/go.mod h1:VLSMwWRlRPazjGYer8pq+4aDrIe1Otj3Yy9HAb0eo3c=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/bytedance/sonic v1.12.8 h1:4xYRVRlXIgvSZ4e8iVTlMF5szgpXd4AfvuWgA8I8lgs=
github.com/bytedance/sonic v1.12.8/go.mod h1:uVvFidNmlt9+wa31S1urfwwthTWteBgG0hWuoKAXTx8=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/bytedance/sonic/loader v0.2.3 h1:yctD0Q3v2NOGfSWPLPvG2ggA2kV6TS6s4wioyEqssH0=
github.com/bytedance/sonic/loader v0.2.3/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4=
github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec=
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/elastic/elastic-transport-go/v8 v8.6.0 h1:Y2S/FBjx1LlCv5m6pWAF2kDJAHoSjSRSJCApolgfthA=
github.com/elastic/elastic-transport-go/v8 v8.6.0/go.mod h1:YLHer5cj0csTzNFXoNQ8qhtGY1GTvSqPnKWKaqQE3Hk=
github.com/elastic/go-elasticsearch/v8 v8.17.0 h1:e9cWksE/Fr7urDRmGPGp47Nsp4/mvNOrU8As1l2HQQ0=
github.com/elastic/go-elasticsearch/v8 v8.17.0/go.mod h1:lGMlgKIbYoRvay3xWBeKahAiJOgmFDsjZC39nmO3H64=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=
github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.24.0 h1:KHQckvo8G6hlWnrPX4NJJ+aBfWNAE/HH+qdL2cBpCmg=
github.com/go-playground/validator/v10 v10.24.0/go.mod h1:GGzBIJMuE98Ic/kJsBXbz1x/7cByt++cQ+YOuDM5wus=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY=
github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/nats-io/nats.go v1.39.0 h1:2/yg2JQjiYYKLwDuBzV0FbB2sIV+eFNkEevlRi4n9lI=
github.com/nats-io/nats.go v1.39.0/go.mod h1:MgRb8oOdigA6cYpEPhXJuRVH6UE/V4jblJ2jQ27IXYM=
github.com/nats-io/nkeys v0.4.9 h1:qe9Faq2Gxwi6RZnZMXfmGMZkg3afLLOtrU+gDZJ35b0=
github.com/nats-io/nkeys v0.4.9/go.mod h1:jcMqs+FLG+W5YO36OX6wFIFcmpdAns+w1Wm6D3I/evE=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/oklog/ulid/v2 v2.1.0 h1:+9lhoxAP56we25tyYETBBY1YLA2SaoLvUFgrP2miPJU=
github.com/oklog/ulid/v2 v2.1.0/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
github.com/tklauser/numcpus v0.9.0 h1:lmyCHtANi8aRUgkckBgoDk1nHCux3n2cgkJLXdQGPDo=
github.com/tklauser/numcpus v0.9.0/go.mod h1:SN6Nq1O3VychhC1npsWostA+oW+VOQTxZrS604NSRyI=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.etcd.io/etcd/api/v3 v3.5.18 h1:Q4oDAKnmwqTo5lafvB+afbgCDF7E35E4EYV2g+FNGhs=
go.etcd.io/etcd/api/v3 v3.5.18/go.mod h1:uY03Ob2H50077J7Qq0DeehjM/A9S8PhVfbQ1mSaMopU=
go.etcd.io/etcd/client/pkg/v3 v3.5.18 h1:mZPOYw4h8rTk7TeJ5+3udUkfVGBqc+GCjOJYd68QgNM=
go.etcd.io/etcd/client/pkg/v3 v3.5.18/go.mod h1:BxVf2o5wXG9ZJV+/Cu7QNUiJYk4A29sAhoI5tIRsCu4=
go.etcd.io/etcd/client/v3 v3.5.18 h1:nvvYmNHGumkDjZhTHgVU36A9pykGa2K4lAJ0yY7hcXA=
go.etcd.io/etcd/client/v3 v3.5.18/go.mod h1:kmemwOsPU9broExyhYsBxX4spCTDX3yLgPMWtpBXG6E=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4=
go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU=
go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU=
go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ=
go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/arch v0.14.0 h1:z9JUEZWr8x4rR0OU6c4/4t6E6jOZ8/QBS2bBYBm4tx4=
golang.org/x/arch v0.14.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/genproto/googleapis/api v0.0.0-20250204164813-702378808489 h1:fCuMM4fowGzigT89NCIsW57Pk9k2D12MMi2ODn+Nk+o=
google.golang.org/genproto/googleapis/api v0.0.0-20250204164813-702378808489/go.mod h1:iYONQfRdizDB8JJBybql13nArx91jcUk7zCXEsOofM4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250204164813-702378808489 h1:5bKytslY8ViY0Cj/ewmRtrWHW64bNF03cAatUUFCdFI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250204164813-702378808489/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk=
google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ=
google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.5.11 h1:ubBVAfbKEUld/twyKZ0IYn9rSQh448EdelLYk9Mv314=
gorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=

View File

@@ -8,31 +8,30 @@ import (
var Response Reply
type Reply struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
Code int32 `json:"code"`
Message string `json:"message"`
Result any `json:"result"`
}
func (reply *Reply) Success(ctx *gin.Context, data any) {
reply.Code = 200
reply.Code = 0
reply.Result = data
reply.Message = ""
if data == nil {
reply.Data = ""
reply.Result = ""
}
ctx.JSON(200, reply)
return
}
func (reply *Reply) Error(ctx *gin.Context, err error) {
reply.Code = 500
reply.Result = ""
// Status code defaults to 500
e, ok := status.FromError(err)
if ok {
reply.Code = int(e.Code())
reply.Code = int32(e.Code())
}
reply.Msg = e.Message()
reply.Message = e.Message()
// Send error
ctx.JSON(200, reply)
return
}

View File

@@ -17,14 +17,14 @@ var (
type service struct{}
func (s *service) Register(cli *clientv3.Client, serviceName string, port int) error {
func (s *service) Register(cli *clientv3.Client, serviceName string, port string) error {
lease := clientv3.NewLease(cli)
grantResp, err := lease.Grant(context.TODO(), 5)
if err != nil {
return err
}
serviceAddr := utils.GetLocationIP() + ":" + utils.Int2String(port)
serviceAddr := utils.GetLocationIP() + ":" + port
key := RootPrefix + serviceName + "/" + utils.Int642String(time.Now().UnixNano())
_, err = cli.KV.Put(context.TODO(), key, serviceAddr, clientv3.WithLease(grantResp.ID))

View File

@@ -58,8 +58,8 @@ var (
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
const (
signKey = "8E853B589944FF7A56BEF02AAA51D6F4"
LICENCE_KEY = "TRAIN_LICENCE_KEY"
signKey = "1F36659EC27CFFF849E068EA80B1A4CA"
LICENCE_KEY = "BLOCKS_KEY"
)
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -69,13 +69,13 @@ func init() {
}
func WatchCheckLicence(licPath, licName string) {
for {
utils.SetInterval(func() {
if CheckLicence(licPath, licName) == false {
log.Println("授权文件失效,请重新部署授权文件:", licPath)
os.Exit(99)
}
time.Sleep(time.Hour * 1)
}
}, time.Hour*1)
}
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

18
middleware/cors.go Normal file
View File

@@ -0,0 +1,18 @@
package middleware
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func Cors() gin.HandlerFunc {
return cors.New(cors.Config{
AllowAllOrigins: true,
AllowHeaders: []string{
"Origin", "Content-Length", "Content-Type", "Workspace", "Request-Id", "Authorization", "Token",
},
AllowMethods: []string{
"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS",
},
})
}

73
middleware/jwt.go Normal file
View File

@@ -0,0 +1,73 @@
package middleware
import (
"encoding/json"
"log"
"net/http"
"time"
"git.apinb.com/bsm-sdk/core/crypto/encipher"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/types"
"github.com/gin-gonic/gin"
)
func JwtAuth(time_verify bool) gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头中获取 Authorization
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
log.Printf("获取token异常:%v\n", "Authorization header is required")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
c.Abort()
return
}
// 提取Token
claims, err := encipher.ParseTokenAes(authHeader)
if err != nil || claims == nil {
log.Printf("提取token异常:%v\n", err)
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token is required"})
c.Abort()
return
}
// 检测是否需要验证token时间
if time_verify {
// 判断时间claims.ExpiresAt
if time.Now().Unix() > claims.ExpiresAt {
log.Println("token过期请重新获取:", "Token has expired")
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token has expired"})
c.Abort()
return
}
}
// 将解析后的 Token 存储到上下文中
c.Set("Auth", claims)
// 如果 Token 有效,继续处理请求
c.Next()
}
}
// 获取上下文用户登录信息
func ParseAuth(c *gin.Context) (*types.JwtClaims, error) {
claims, ok := c.Get("Auth")
if !ok {
log.Printf("获取登录信息异常: %v", errcode.ErrJWTAuthNotFound)
return nil, errcode.ErrJWTAuthNotFound
}
json_claims, err := json.Marshal(claims)
if err != nil {
log.Printf("解析json异常: %v", err)
return nil, errcode.ErrJsonMarshal
}
var auth *types.JwtClaims
if err := json.Unmarshal(json_claims, &auth); err != nil {
log.Printf("解析json异常: %v", err)
return nil, errcode.ErrJsonUnmarshal
}
return auth, nil
}

16
middleware/mode.go Normal file
View File

@@ -0,0 +1,16 @@
package middleware
import (
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/vars"
"github.com/gin-gonic/gin"
)
func Mode(app *gin.Engine) {
// 设置gin模式
if env.Runtime.Mode == vars.RUN_MODE_PROD {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
}

14
oplog/new.go Normal file
View File

@@ -0,0 +1,14 @@
package oplog
import (
"encoding/json"
"git.apinb.com/bsm-sdk/core/utils"
)
func New(endpoint string, data []*LogItem) {
jsonBytes, _ := json.Marshal(data)
go utils.HttpPost(endpoint, nil, jsonBytes)
}

24
oplog/types.go Normal file
View File

@@ -0,0 +1,24 @@
package oplog
type LogItem struct {
OpID uint `json:"op_id"`
OpName string `json:"op_name"`
OpType string `json:"op_type"`
Text string `json:"text"`
Code string `json:"code"`
Level uint `json:"level"`
Ip string `json:"ip"`
Module string `json:"module"`
Encry bool `json:"encry"`
}
var (
Type_Login string = "login"
Type_Logout string = "logout"
Type_Register string = "register"
Type_Update string = "update"
Type_Delete string = "delete"
Type_Query string = "query"
Type_Other string = "other"
Type_Create string = "create"
)

View File

@@ -3,28 +3,36 @@ package print
import (
"fmt"
"log"
"os"
)
var logger *log.Logger
func init() {
logger = log.New(os.Stdout, "", 0) // 创建一个新的 Logger 实例,不带任何标志
logger.SetFlags(log.Ldate | log.Ltime)
}
// record INFO message. Color White
func Info(format string, a ...interface{}) {
message := fmt.Sprintf("\033[37m[Info] "+format+"\033[0m\n", a...)
log.Print(message)
logger.Print(message)
}
// record Warn message. Color Orange
func Warn(format string, a ...interface{}) {
message := fmt.Sprintf("\033[33m[Warn] "+format+"\033[0m\n", a...)
log.Print(message)
logger.Print(message)
}
// record Success message. Color Green
func Success(format string, a ...interface{}) {
message := fmt.Sprintf("\033[32m[Success] "+format+"\033[0m\n", a...)
log.Print(message)
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{}) {
message := fmt.Sprintf("\033[31m[Error] "+format+"\033[0m\n", a...)
log.Print(message)
logger.Print(message)
}

60
service/meta.go Normal file
View File

@@ -0,0 +1,60 @@
package service
import (
"context"
"git.apinb.com/bsm-sdk/core/crypto/encipher"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/utils"
"google.golang.org/grpc/metadata"
)
// 解析Context中MetaData的数据
type ParseOptions struct {
RoleValue string // 判断角色的值
MustPrivateAllow bool // 是否只允许私有IP访问
}
func ParseMetaCtx(ctx context.Context, opts *ParseOptions) (*types.JwtClaims, error) {
// 解析metada中的信息并验证
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errcode.ErrJWTAuthNotFound
}
var Authorizations []string = md.Get("authorization")
if len(Authorizations) == 0 || Authorizations[0] == "" {
return nil, errcode.ErrJWTAuthNotFound
}
claims, err := encipher.ParseTokenAes(Authorizations[0])
if err != nil {
return nil, err
}
if opts != nil {
if !checkRole(claims, "role", opts.RoleValue) {
return nil, errcode.ErrPermissionDenied
}
if opts.MustPrivateAllow {
if utils.IsPublicIP(claims.Client) {
return nil, errcode.ErrPermissionDenied
}
}
}
return claims, nil
}
func checkRole(claims *types.JwtClaims, roleKey, roleValue string) bool {
if roleValue == "" {
return true
}
if role, exists := claims.Extend[roleKey]; !exists || role != roleValue {
return false
} else {
return true
}
}

132
service/register.go Normal file
View File

@@ -0,0 +1,132 @@
package service
import (
"context"
"strings"
"time"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
clientv3 "go.etcd.io/etcd/client/v3"
)
// ServiceRegister 创建租约注册服务
type ServiceRegister struct {
cli *clientv3.Client //etcd client
leaseID clientv3.LeaseID //租约ID
//租约keepalieve相应chan
keepAliveChan <-chan *clientv3.LeaseKeepAliveResponse
key string //key
val string //value
}
// NewRegister 注册服务至路由表.
//
// ec:EtcdConfig;
//
// routeKey: ServiceRouteRootPrefix + ServiceKey + "/" + utils.GetLocationIP() + addr;
//
// gs:grpc.Server;
func RegisterService(cli *clientv3.Client, routeKey string, methods []string, lease int64) (*ServiceRegister, error) {
ser := &ServiceRegister{
cli: cli,
key: routeKey,
val: strings.Join(methods, ","),
}
//申请租约设置时间keepalive
if err := ser.putKeyWithLease(lease); err != nil {
return nil, err
}
return ser, nil
}
// 设置租约
func (s *ServiceRegister) putKeyWithLease(lease int64) error {
//设置租约时间
resp, err := s.cli.Grant(context.Background(), lease)
if err != nil {
return err
}
//注册服务并绑定租约
_, err = s.cli.Put(context.Background(), s.key, s.val, clientv3.WithLease(resp.ID))
if err != nil {
return err
}
//设置续租 定期发送需求请求
leaseRespChan, err := s.cli.KeepAlive(context.Background(), resp.ID)
if err != nil {
return err
}
s.leaseID = resp.ID
s.keepAliveChan = leaseRespChan
return nil
}
// ListenLeaseRespChan 监听 续租情况
func (s *ServiceRegister) ListenLeaseRespChan() {
for {
select {
case leaseKeepResp := <-s.keepAliveChan:
if leaseKeepResp == nil {
//log.Println("close lease.")
return
} else {
goto END
}
}
END:
time.Sleep(500 * time.Millisecond)
}
}
// Close 注销服务
func (s *ServiceRegister) Close() error {
//撤销租约
if _, err := s.cli.Revoke(context.Background(), s.leaseID); err != nil {
return err
}
return s.cli.Close()
}
func (s *ServiceRegister) SetAnonymous(key string, urls []string) {
// remove reppeat, clear service all anonymous uri.
anonymous, err := s.cli.Get(context.Background(), key)
if err != nil {
print.Error("[BSM Register] Get Anonymous Fail: %v", err)
return
}
var as []string
if len(anonymous.Kvs) > 0 {
val := string(anonymous.Kvs[0].Value)
as = strings.Split(val, ",")
}
as = append(clearService(as), urls...)
newAnonymous := strings.Join(as, ",")
// put anonymous to etcd
_, err = s.cli.Put(context.Background(), key, newAnonymous)
if err != nil {
print.Error("[BSM Register] Anonymous Fail.")
} else {
print.Info("[BSM Register] Anonymous: %s", newAnonymous)
}
}
func clearService(as []string) (out []string) {
for _, v := range as {
if len(v) >= len(vars.ServiceKey) {
if v[0:len(vars.ServiceKey)] != vars.ServiceKey {
out = append(out, v)
}
}
}
return
}

125
service/service.go Normal file
View File

@@ -0,0 +1,125 @@
package service
import (
"context"
"log"
"net"
"os"
"strconv"
"strings"
"net/http"
gwRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
clientv3 "go.etcd.io/etcd/client/v3"
"google.golang.org/grpc"
)
type (
// RegisterFn defines the method to register a server.
RegisterFn func(*grpc.Server)
Service struct {
GrpcSrv *grpc.Server
Opts *Options
}
Options struct {
Addr string
EtcdClient *clientv3.Client
MsConf *conf.MicroServiceConf
GatewayConf *conf.GatewayConf
GatewayCtx context.Context
GatewayMux *gwRuntime.ServeMux
}
)
func New(srv *grpc.Server, opts *Options) *Service {
return &Service{GrpcSrv: srv, Opts: opts}
}
func Addr(ip string, port int) string {
return net.JoinHostPort(ip, strconv.Itoa(port))
}
func (s *Service) Start() {
print.Info("[BSM - %s] Service Starting ...", vars.ServiceKey)
// register to etcd.
if s.Opts.MsConf != nil && s.Opts.MsConf.Enable {
if s.Opts.EtcdClient == nil {
print.Error("[BSM Register] Etcd Client is nil.")
os.Exit(1)
}
print.Info("[BSM - %s] Registering Service to Etcd ...", vars.ServiceKey)
// get methods
methods := FoundGrpcMethods(s.GrpcSrv)
// set router key
routerKey := vars.ServiceRootPrefix + "Router/" + env.Runtime.Workspace + "/" + strings.ToLower(vars.ServiceKey) + "/" + s.Opts.Addr
// register to etcd
register, err := RegisterService(s.Opts.EtcdClient, routerKey, methods, vars.ServiceLease)
if err != nil {
log.Panicf("[ERROR] %s Service Register:%s \n", vars.ServiceKey, err.Error())
}
anonKey := vars.ServiceRootPrefix + "Router/" + env.Runtime.Workspace + "/"
register.SetAnonymous(anonKey, s.Opts.MsConf.Anonymous)
// service register lease
go register.ListenLeaseRespChan()
}
// run grpc srv.
tcpListen, err := net.Listen("tcp", s.Opts.Addr)
if err != nil {
panic(err)
}
go func() {
if err := s.GrpcSrv.Serve(tcpListen); err != nil {
panic(err)
}
}()
print.Success("[BSM - %s] Grpc %s Runing Success !", vars.ServiceKey, s.Opts.Addr)
if s.Opts.GatewayConf != nil && s.Opts.GatewayConf.Enable {
addr := Addr("0.0.0.0", s.Opts.GatewayConf.Port)
go s.Gateway(s.Opts.Addr, addr)
print.Success("[BSM - %s] Http %s Runing Success!", vars.ServiceKey, addr)
}
select {}
}
func (s *Service) Gateway(grpcAddr string, httpAddr string) {
// 1. 定义一个context
_, cancel := context.WithCancel(s.Opts.GatewayCtx)
defer cancel()
http.ListenAndServe(httpAddr, s.Opts.GatewayMux)
}
func (s *Service) Stop() {
s.GrpcSrv.GracefulStop()
}
// found grpc methods.
func FoundGrpcMethods(s *grpc.Server) []string {
var mothods []string
for key, srv := range s.GetServiceInfo() {
srvName := strings.Split(key, ".")[1]
for _, mn := range srv.Methods {
mothods = append(mothods, srvName+"."+mn.Name)
}
}
return mothods
}

65
third/wechat.go Normal file
View File

@@ -0,0 +1,65 @@
package third
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
)
func WeChat_Decrypt(sessionKey, encryptedData, iv string) (string, error) {
aesKey, err := base64.StdEncoding.DecodeString(sessionKey)
if err != nil {
return "", err
}
cipherText, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
return "", err
}
ivBytes, err := base64.StdEncoding.DecodeString(iv)
if err != nil {
return "", err
}
block, err := aes.NewCipher(aesKey)
if err != nil {
return "", err
}
mode := cipher.NewCBCDecrypter(block, ivBytes)
mode.CryptBlocks(cipherText, cipherText)
cipherText, err = WeChat_Pkcs7Unpad(cipherText, block.BlockSize())
if err != nil {
return "", err
}
return string(cipherText), nil
}
// pkcs7Unpad returns slice of the original data without padding
func WeChat_Pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
var (
// ErrInvalidBlockSize block size不合法
ErrInvalidBlockSize = errors.New("invalid block size")
// ErrInvalidPKCS7Data PKCS7数据不合法
ErrInvalidPKCS7Data = errors.New("invalid PKCS7 data")
// ErrInvalidPKCS7Padding 输入padding失败
ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
)
if blockSize <= 0 {
return nil, ErrInvalidBlockSize
}
if len(data)%blockSize != 0 || len(data) == 0 {
return nil, ErrInvalidPKCS7Data
}
c := data[len(data)-1]
n := int(c)
if n == 0 || n > len(data) {
return nil, ErrInvalidPKCS7Padding
}
for i := 0; i < n; i++ {
if data[len(data)-n+i] != c {
return nil, ErrInvalidPKCS7Padding
}
}
return data[:len(data)-n], nil
}

View File

@@ -10,62 +10,68 @@ type (
// sql options
SqlOptions struct {
MaxIdleConns int
MaxOpenConns int
MaxIdleConns int `gorm:"column:max_idle_conns;" json:"max_idle_conns"`
MaxOpenConns int `gorm:"column:max_open_conns;" json:"max_open_conns"`
ConnMaxLifetime time.Duration
LogStdout bool
Debug bool
LogStdout bool `gorm:"column:log_stdout;" json:"log_stdout"`
Debug bool `gorm:"column:debug;" json:"debug"`
}
// standard ID,Identity definition.
Std_IDIdentity struct {
ID uint `gorm:"primarykey;" json:"id"`
ID uint `gorm:"column:id;primarykey;" json:"id"`
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为ULID
}
// standard ID,Created,Updated,Deleted definition.
Std_IICUDS struct {
ID uint `gorm:"primarykey;" json:"id"`
ID uint `gorm:"column:id;primarykey;" json:"id"`
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为ULID
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
Status int8 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
CreatedAt time.Time `gorm:"column:created_at;type:TIMESTAMP;" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:TIMESTAMP;" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:TIMESTAMP;index;" json:"deleted_at"`
Status int8 `gorm:"column:status;default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
}
// standard ID,Identity,Created,Updated,Deleted,Status definition.
Std_ICUD struct {
ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;" json:"deleted_at"`
ID uint `gorm:"column:id;primarykey;" json:"id"`
CreatedAt time.Time `gorm:"column:created_at;" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at;type:TIMESTAMP;" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at;type:TIMESTAMP;index;" json:"deleted_at"`
}
// standard ID,Created definition.
Std_IdCreated struct {
ID uint `gorm:"primarykey;" json:"id"`
CreatedAt time.Time `json:"created_at"`
ID uint `gorm:"column:id;primarykey;" json:"id"`
CreatedAt time.Time `gorm:"column:created_at;type:TIMESTAMP;" json:"created_at"`
}
// standard PassportID,PassportIdentity definition.
Std_Passport struct {
PassportID uint `gorm:"column:passport_id;Index;" json:"passport_id"`
PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;" json:"passport_identity"` // 用户唯一标识24位NanoID,36位为ULID
PassportIdentity string `gorm:"column:passport_identity;type:varchar(36);Index;" json:"passport_identity"` // 用户唯一标识24位NanoID,36位为UUID
}
// standard OwnerID,OwnerIdentity definition.
Std_Owner struct {
OwnerID uint `gorm:"column:owner_id;Index;" json:"owner_id"`
OwnerIdentity string `gorm:"column:owner_identity;type:varchar(36);Index;" json:"owner_identity"` // 用户唯一标识24位NanoID,36位为UUID
}
// standard ID definition.
Std_ID struct {
ID uint `gorm:"primarykey;" json:"id"`
ID uint `gorm:"column:id;primarykey;" json:"id"`
}
// standard Identity definition.
Std_Identity struct {
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为ULID
Identity string `gorm:"column:identity;type:varchar(36);uniqueIndex;" json:"identity"` // 唯一标识24位NanoID,36位为UUID
}
// standard Status definition.
Std_Status struct {
Status int8 `gorm:"default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
Status int64 `gorm:"column:status;default:0;index;" json:"status"` // 状态默认为0-1禁止1为正常
}
)

View File

@@ -13,4 +13,5 @@ type JwtClaims struct {
Owner any `json:"owner"`
Role string `json:"role"`
ExpiresAt int64 `json:"exp"`
SsoToken string `json:"sso_token"`
}

View File

@@ -6,36 +6,48 @@ import (
"strings"
)
// 字符串转Int
// String2Int 字符串转Int
//
// intStr数字的字符串
func String2Int(intStr string) (intNum int) {
intNum, _ = strconv.Atoi(intStr)
intNum, err := strconv.Atoi(intStr)
if err != nil {
return 0
}
return
}
// 字符串转Int64
// String2Int64 字符串转Int64
//
// intStr数字的字符串
func String2Int64(intStr string) (int64Num int64) {
intNum, _ := strconv.Atoi(intStr)
intNum, err := strconv.Atoi(intStr)
if err != nil {
return 0
}
int64Num = int64(intNum)
return
}
// 字符串转Float64
// String2Float64 字符串转Float64
//
// floatStr小数点数字的字符串
func String2Float64(floatStr string) (floatNum float64) {
floatNum, _ = strconv.ParseFloat(floatStr, 64)
floatNum, err := strconv.ParseFloat(floatStr, 64)
if err != nil {
return 0
}
return
}
// 字符串转Float32
// String2Float32 字符串转Float32
//
// floatStr小数点数字的字符串
func String2Float32(floatStr string) (floatNum float32) {
floatNum64, _ := strconv.ParseFloat(floatStr, 32)
floatNum64, err := strconv.ParseFloat(floatStr, 32)
if err != nil {
return 0
}
floatNum = float32(floatNum64)
return
}

View File

@@ -25,11 +25,17 @@ func CreateDir(dirName string) bool {
}
func GetRunPath() string {
path, _ := os.Executable()
path, err := os.Executable()
if err != nil {
return ""
}
return path
}
func GetCurrentPath() string {
path, _ := os.Getwd()
path, err := os.Getwd()
if err != nil {
return ""
}
return path
}
}

View File

@@ -1,6 +1,10 @@
package utils
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
)
@@ -12,7 +16,7 @@ func If(condition bool, trueValue, falseValue interface{}) interface{} {
return falseValue
}
//如果首字母是小写字母, 则变换为大写字母
// 如果首字母是小写字母, 则变换为大写字母
func FirstToUpper(str string) string {
if str == "" {
return ""
@@ -33,3 +37,11 @@ func ParseParams(in map[string]string) map[string]interface{} {
}
return out
}
func PrintJson(v any) {
jsonBy, _ := json.Marshal(v)
var out bytes.Buffer
json.Indent(&out, jsonBy, "", "\t")
out.WriteTo(os.Stdout)
fmt.Printf("\n")
}

View File

@@ -2,10 +2,21 @@ package utils
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
)
const (
B = 1
KB = 1024 * B
MB = 1024 * KB
GB = 1024 * MB
)
// 将字符串写入文件
func StringToFile(path, content string) error {
startF, err := os.Create(path)
if err != nil {
@@ -18,3 +29,132 @@ func StringToFile(path, content string) error {
}
return nil
}
// 文件复制
func CopyFile(src, dst string) (int64, error) {
sourceFileStat, err := os.Stat(src)
if err != nil {
return 0, err
}
if !sourceFileStat.Mode().IsRegular() {
return 0, fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return 0, err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destination.Close()
nBytes, err := io.Copy(destination, source)
return nBytes, err
}
func FileSize(fp string) string {
fileInfo, err := os.Stat(fp)
if err != nil {
return "0 B"
}
bytes := fileInfo.Size()
switch {
case bytes >= GB:
return fmt.Sprintf("%.2f GB", float64(bytes)/float64(GB))
case bytes >= MB:
return fmt.Sprintf("%.2f MB", float64(bytes)/float64(MB))
case bytes >= KB:
return fmt.Sprintf("%.2f KB", float64(bytes)/float64(KB))
default:
return fmt.Sprintf("%d B", bytes)
}
}
// 递归遍历文件夹
// rootDir: 文件夹根目录
// s: 存储文件名的切片
// filter: 过滤条件:".git", ".idea", ".vscode", ".gitignore", ".gitea", ".github", ".golangci.yml", "*.pyc"
func FileTreeByFilter(rootDir string, s []string, filter []string) ([]string, error) {
rd, err := os.ReadDir(rootDir)
if err != nil {
return s, err
}
for _, fi := range rd {
// 检查文件名是否匹配任何一个过滤模式
matched := false
for _, item := range filter {
exists, err := filepath.Match(item, fi.Name())
if err != nil {
continue
}
if exists {
matched = true
break
}
}
if matched {
continue
}
if fi.IsDir() {
fullDir := rootDir + "/" + fi.Name()
s, err = FileTreeByFilter(fullDir, s, filter)
if err != nil {
return s, err
}
} else {
fullName := rootDir + "/" + fi.Name()
s = append(s, fullName)
}
}
return s, nil
}
// 递归遍历文件夹
// rootDir: 文件夹根目录
// s: 存储文件名的切片
// allow: 允许条件:".zip", ".check"
func FileTreeBySelect(rootDir string, s []string, allow []string) ([]string, error) {
rd, err := os.ReadDir(rootDir)
if err != nil {
return s, err
}
for _, fi := range rd {
// 检查文件名是否匹配任何一个过滤模式
matched := false
for _, item := range allow {
exists, err := filepath.Match(item, fi.Name())
if err != nil {
continue
}
if exists {
matched = true
break
}
}
if !matched {
continue
}
if fi.IsDir() {
fullDir := rootDir + "/" + fi.Name()
s, err = FileTreeBySelect(fullDir, s, allow)
if err != nil {
return s, err
}
} else {
fullName := rootDir + "/" + fi.Name()
s = append(s, fullName)
}
}
return s, nil
}

View File

@@ -1,9 +1,14 @@
package utils
import (
"github.com/google/uuid"
ulid "github.com/oklog/ulid/v2"
)
func UUID() string {
return uuid.Must(uuid.NewV7()).String()
}
// remove nanoid,uuid,replace to ulid
func ULID() string {
return ulid.Make().String()

View File

@@ -2,6 +2,7 @@ package utils
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
@@ -9,6 +10,7 @@ import (
"net/http"
"os"
"strconv"
"strings"
)
func IsPublicIP(ipString string) bool {
@@ -32,24 +34,55 @@ func IsPublicIP(ipString string) bool {
}
// Get Location IP .
func GetLocationIP() string {
addrs, err := net.InterfaceAddrs()
func GetLocationIP() (localIp string) {
localIp = "127.0.0.1"
// Get all network interfaces
interfaces, err := net.Interfaces()
if err != nil {
return ""
return
}
ip := ""
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ip = ipnet.IP.String()
break
for _, iface := range interfaces {
// Skip the loopback interface
if iface.Flags&net.FlagLoopback != 0 {
continue
}
// Get addresses associated with the interface
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
// Check if the address is an IPNet
ipnet, ok := addr.(*net.IPNet)
if !ok || ipnet.IP.IsLoopback() {
continue
}
// Get the IP address
ip := ipnet.IP.To4()
if ip == nil {
continue
}
// Skip IP addresses in the 169.254.x.x range
if strings.HasPrefix(ip.String(), "169.254") {
continue
}
// Skip IP addresses in the 169.254.x.x range
if strings.HasPrefix(ip.String(), "26.26") {
continue
}
// Return the first valid IP address found
return ip.String()
}
}
if ip == "" {
return ""
}
return ip
return
}
func LocalIPv4s() ([]string, error) {
@@ -89,6 +122,15 @@ func HttpGet(url string) ([]byte, error) {
return body, err
}
func HttpPostJSON(url string, header map[string]string, data map[string]any) ([]byte, error) {
bytes, err := json.Marshal(data)
if err != nil {
return nil, err
}
return HttpPost(url, header, bytes)
}
func HttpPost(url string, header map[string]string, data []byte) ([]byte, error) {
var err error
reader := bytes.NewBuffer(data)

14
utils/time.go Normal file
View File

@@ -0,0 +1,14 @@
package utils
import (
"time"
)
func Time2String(layout string, t time.Time) string {
return t.Format(layout)
}
func String2Time(layout, in string) time.Time {
t, _ := time.ParseInLocation(layout, in, time.Local)
return t
}

View File

@@ -4,5 +4,5 @@ import "time"
var (
// cache def value
JwtExpireDay time.Duration = 1 * 24 * time.Hour
JwtExpire time.Duration = 1 * 24 * time.Hour
)

View File

@@ -4,4 +4,7 @@ var (
RUN_MODE_DEV = "dev"
RUN_MODE_TEST = "test"
RUN_MODE_PROD = "prod"
ServiceLease int64 = 60
ServiceRootPrefix string = "/"
)

View File

@@ -5,4 +5,6 @@ const (
NormalStatus = 1
// DisabledStatus .
DisabledStatus = -1
OK string = "OK"
)

27
with/databases.go Normal file
View File

@@ -0,0 +1,27 @@
package with
import (
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/database"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/types"
"git.apinb.com/bsm-sdk/core/vars"
"gorm.io/gorm"
)
func Databases(cfg *conf.DBConf, db *gorm.DB, opts *types.SqlOptions) {
if cfg == nil || len(cfg.Source) == 0 {
panic("No Database Source Found !")
}
// print inform.
print.Info("[BSM - %s] Databases: %v", vars.ServiceKey, cfg)
var err error
db, err = database.NewDatabase(cfg.Driver, cfg.Source, opts)
if err != nil {
print.Error("Database Init Failed !")
panic(err)
}
return
}

54
with/etcd.go Normal file
View File

@@ -0,0 +1,54 @@
package with
import (
"time"
"git.apinb.com/bsm-sdk/core/conf"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
"go.etcd.io/etcd/client/pkg/v3/transport"
clientv3 "go.etcd.io/etcd/client/v3"
)
func Etcd(cfg *conf.EtcdConf, cli *clientv3.Client) {
if cfg == nil || len(cfg.Endpoints) == 0 {
return
}
etcdCfg := clientv3.Config{
Endpoints: cfg.Endpoints,
DialTimeout: 5 * time.Second,
}
if cfg.Passwd != nil {
etcdCfg.Username = cfg.Passwd.Account
etcdCfg.Password = cfg.Passwd.Password
}
if cfg.TLS != nil {
tlsInfo := transport.TLSInfo{
TrustedCAFile: cfg.TLS.CaFile,
CertFile: cfg.TLS.CertFile,
KeyFile: cfg.TLS.KeyFile,
}
tlsConfig, err := tlsInfo.ClientConfig()
if err != nil {
print.Error(errcode.ErrEtcd.Error())
panic(err)
}
etcdCfg.TLS = tlsConfig
}
var err error
cli, err = clientv3.New(etcdCfg)
if err != nil {
print.Error(errcode.ErrEtcd.Error())
panic(err)
}
// print inform.
print.Info("[BSM - %s] Service Center: %v", vars.ServiceKey, cfg.Endpoints)
return
}

35
with/memory.go Normal file
View File

@@ -0,0 +1,35 @@
package with
import (
"context"
"time"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
"github.com/allegro/bigcache/v3"
)
func Memory(cli *bigcache.BigCache, opts *bigcache.Config) {
if opts == nil {
opts = &bigcache.Config{
Shards: 1024,
LifeWindow: 10 * time.Minute,
CleanWindow: 5 * time.Minute,
MaxEntriesInWindow: 1000 * 10 * 60,
MaxEntrySize: 500,
Verbose: true,
HardMaxCacheSize: 8192,
OnRemove: nil,
OnRemoveWithReason: nil,
}
}
var err error
cli, err = bigcache.New(context.Background(), *opts)
if err != nil {
print.Error("Memory Cache Fatal Error")
panic(err)
}
print.Success("[BSM - %s] Memory Cache: Shards=%d, MaxEntrySize=%d", vars.ServiceKey, opts.Shards, opts.MaxEntrySize)
}

16
with/redis.go Normal file
View File

@@ -0,0 +1,16 @@
package with
import (
"git.apinb.com/bsm-sdk/core/cache/redis"
"git.apinb.com/bsm-sdk/core/print"
"git.apinb.com/bsm-sdk/core/vars"
)
func RedisCache(cfg string, cli *redis.RedisClient) {
if cfg != "" {
cli = redis.New(cfg, vars.ServiceKey)
// print inform.
print.Info("[BSM - %s] Cache: %s, DBIndex: %d", vars.ServiceKey, cfg, cli.DB)
}
}