Compare commits

..

8 Commits

Author SHA1 Message Date
75aa6ae647 dev 2025-09-23 13:09:27 +08:00
f681f0bb17 ```
refactor(service): 优化Use函数参数类型

移除Use函数中initFunc参数的指针包装,直接使用func() error类型。
简化函数内部调用逻辑,提升代码可读性和健壮性。
```
2025-09-23 12:41:31 +08:00
44319d03b9 ```
refactor(database): 移除全局初始化函数定义

将数据库初始化函数从 database 包中移除,避免全局状态污染。

feat(service): 新增 Use 方法用于执行初始化函数

在 Service 结构体中添加 Use 方法,允许传入并执行初始化函数。
如果函数执行失败,则打印错误并 panic。

refactor(with): 删除旧的初始化逻辑包

删除 with 包中与数据库初始化相关的旧逻辑,统一初始化入口。
```
2025-09-23 12:37:00 +08:00
2f57edd277 ```
refactor(database): 重构数据库初始化逻辑

移除 NewDatabase 函数中的 Init 参数,改用 InitFunc 变量进行初始化操作。
更新 MigrateTables 附近的注释,明确说明 InitFunc 的用途。
删除函数内对 Init 参数的执行逻辑,确保代码简洁性。
```
2025-09-23 11:28:33 +08:00
cf0ee224f7 ```
refactor(database): 调整数据库初始化函数参数传递方式

将 Init 函数参数从全局变量改为通过 NewDatabase 函数参数传入,
使初始化逻辑更清晰、可控。同时优化代码格式,去除多余空行,
提升代码可读性。
```
2025-09-23 11:02:25 +08:00
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
10 changed files with 349 additions and 46 deletions

View File

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

View File

@@ -104,31 +104,41 @@ func AesDecryptCBC(cryted string) (b []byte, err error) {
return orig, nil return orig, nil
} }
// PKCS7Padding 使用PKCS7填充法对明文进行填充
func PKCS7Padding(ciphertext []byte, blocksize int) []byte { func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
padding := blocksize - len(ciphertext)%blocksize padding := blocksize - len(ciphertext)%blocksize
padtext := bytes.Repeat([]byte{byte(padding)}, padding) padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...) return append(ciphertext, padtext...)
} }
// 去码 // PKCS7UnPadding 去除PKCS7填充
// bug:runtime error: slice bounds out of range [:-22] // bug:runtime error: slice bounds out of range [:-22]
func PKCS7UnPadding(origData []byte, blocksize int) []byte { func PKCS7UnPadding(origData []byte, blocksize int) []byte {
// 检查块大小是否有效
if blocksize <= 0 { if blocksize <= 0 {
return nil return nil
} }
// 检查原始数据是否为空
if origData == nil || len(origData) == 0 { if origData == nil || len(origData) == 0 {
return nil return nil
} }
// 检查数据长度是否为块大小的整数倍
if len(origData)%blocksize != 0 { if len(origData)%blocksize != 0 {
return nil return nil
} }
length := len(origData) length := len(origData)
// 获取填充字节数
unpadding := int(origData[length-1]) unpadding := int(origData[length-1])
// 检查去填充后数据长度是否有效
if length-unpadding <= 0 { if length-unpadding <= 0 {
return nil return nil
} }
// 返回去除填充后的数据
return origData[:(length - unpadding)] return origData[:(length - unpadding)]
} }

View File

@@ -1,3 +1,4 @@
// Package database provides database connection and management functionality
package database package database
import ( import (
@@ -12,9 +13,12 @@ import (
) )
var ( var (
// MigrateTables holds the tables that need to be auto-migrated on database initialization
MigrateTables []any MigrateTables []any
) )
// 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) { func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *gorm.DB, err error) {
driver = strings.ToLower(driver) driver = strings.ToLower(driver)
switch driver { switch driver {
@@ -33,13 +37,13 @@ func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *go
return db, nil return db, nil
} }
// NewMysql 创建MySQL数据库服务 // NewMysql creates a MySQL database service
func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) { func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
//set connection default val. //set connection default val.
if options == nil { if options == nil {
options = &types.SqlOptions{ options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns, MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxIdleConns, MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime, ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false, LogStdout: false,
Debug: true, Debug: true,
@@ -58,7 +62,11 @@ func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err err
} }
// 获取通用数据库对象 sql.DB ,然后使用其提供的功能 // 获取通用数据库对象 sql.DB ,然后使用其提供的功能
sqlDB, _ := gormDb.DB() sqlDB, err := gormDb.DB()
if err != nil {
return nil, err
}
// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。 // SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
sqlDB.SetMaxIdleConns(options.MaxIdleConns) sqlDB.SetMaxIdleConns(options.MaxIdleConns)
// SetMaxOpenConns 设置打开数据库连接的最大数量。 // SetMaxOpenConns 设置打开数据库连接的最大数量。
@@ -76,13 +84,13 @@ func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err err
return gormDb, nil return gormDb, nil
} }
// NewPostgres 创建PostgreSQL数据库服务 // NewPostgres creates a PostgreSQL database service
func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) { func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err error) {
//set connection default val. //set connection default val.
if options == nil { if options == nil {
options = &types.SqlOptions{ options = &types.SqlOptions{
MaxIdleConns: vars.SqlOptionMaxIdleConns, MaxIdleConns: vars.SqlOptionMaxIdleConns,
MaxOpenConns: vars.SqlOptionMaxIdleConns, MaxOpenConns: vars.SqlOptionMaxOpenConns,
ConnMaxLifetime: vars.SqlOptionConnMaxLifetime, ConnMaxLifetime: vars.SqlOptionConnMaxLifetime,
LogStdout: false, LogStdout: false,
Debug: true, Debug: true,
@@ -98,6 +106,19 @@ func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err
gormDb = gormDb.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 { if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...) err = gormDb.AutoMigrate(MigrateTables...)
if err != nil { if err != nil {

View File

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

206
service/address.go Normal file
View File

@@ -0,0 +1,206 @@
package service
import (
"fmt"
"net"
"net/url"
"strings"
)
type NetworkAddress struct {
Protocol string // tcp, tcp4, tcp6, unix, unixpacket
Host string // IP 地址或主机名
Port string // 端口号
Path string // Unix socket 路径
Raw string // 原始字符串
}
// 解析网络地址字符串
// "tcp://0.0.0.0:1212",
//
// "tcp4://127.0.0.1:8080",
// "tcp6://[::1]:8080",
// "unix:///data/app/passport.sock",
// "unixpacket:///tmp/mysql.sock",
// ":8080", // 传统格式
// "/tmp/server.sock", // 传统Unix格式
// "invalid://address", // 错误格式
func ParseNetworkAddress(addr string) (*NetworkAddress, error) {
// 如果包含 ://,按 URL 解析
if strings.Contains(addr, "://") {
return parseURLStyle(addr)
}
// 否则按传统格式解析
return parseTraditionalStyle(addr)
}
// 解析 tcp://0.0.0.0:1212 或 unix:///path/to/socket 格式
func parseURLStyle(addr string) (*NetworkAddress, error) {
u, err := url.Parse(addr)
if err != nil {
return nil, fmt.Errorf("解析URL失败: %w", err)
}
result := &NetworkAddress{
Protocol: u.Scheme,
Raw: addr,
}
switch u.Scheme {
case "tcp", "tcp4", "tcp6":
return parseTCPURL(u, result)
case "unix", "unixpacket":
return parseUnixURL(u, result)
default:
return nil, fmt.Errorf("不支持的协议: %s", u.Scheme)
}
}
// 解析 TCP 类型的 URL
func parseTCPURL(u *url.URL, result *NetworkAddress) (*NetworkAddress, error) {
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
// 如果没有端口,尝试添加默认端口
if strings.Contains(err.Error(), "missing port") {
host = u.Host
port = "0" // 默认端口
} else {
return nil, fmt.Errorf("解析TCP地址失败: %w", err)
}
}
result.Host = host
result.Port = port
// 根据主机地址确定具体的协议类型
if result.Protocol == "tcp" {
result.Protocol = determineTCPProtocol(host)
}
return result, nil
}
// 解析 Unix socket 类型的 URL
func parseUnixURL(u *url.URL, result *NetworkAddress) (*NetworkAddress, error) {
// Unix socket 路径在 URL 的 Path 字段
if u.Path == "" {
return nil, fmt.Errorf("Unix socket 路径不能为空")
}
result.Path = u.Path
// 如果协议是 unix但路径表明需要数据包传输可以自动升级
if result.Protocol == "unix" && strings.Contains(u.Path, "packet") {
result.Protocol = "unixpacket"
}
return result, nil
}
// 根据主机地址确定 TCP 协议类型
func determineTCPProtocol(host string) string {
if host == "" {
return "tcp" // 默认
}
// 解析 IP 地址
ip := net.ParseIP(host)
if ip != nil {
if ip.To4() != nil {
return "tcp4"
}
return "tcp6"
}
// 如果是特殊地址
switch host {
case "0.0.0.0", "127.0.0.1", "localhost":
return "tcp4"
case "::", "::1":
return "tcp6"
default:
return "tcp" // 默认支持双栈
}
}
// 解析传统格式如 ":8080", "127.0.0.1:8080", "/tmp/socket"
func parseTraditionalStyle(addr string) (*NetworkAddress, error) {
result := &NetworkAddress{Raw: addr}
// 检查是否是 Unix socket包含路径分隔符
if strings.Contains(addr, "/") || strings.HasPrefix(addr, "@/") {
result.Protocol = "unix"
result.Path = addr
return result, nil
}
// 否则按 TCP 地址解析
result.Protocol = "tcp"
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("解析地址失败: %w", err)
}
result.Host = host
result.Port = port
result.Protocol = determineTCPProtocol(host)
return result, nil
}
// 获取网络类型用于 net.Dial 或 net.Listen
func (na *NetworkAddress) Network() string {
return na.Protocol
}
// 获取地址字符串用于 net.Dial 或 net.Listen
func (na *NetworkAddress) Address() string {
switch na.Protocol {
case "tcp", "tcp4", "tcp6":
if na.Port == "" {
return na.Host
}
return net.JoinHostPort(na.Host, na.Port)
case "unix", "unixpacket":
return na.Path
default:
return na.Raw
}
}
// 格式化输出
func (na *NetworkAddress) String() string {
switch na.Protocol {
case "tcp", "tcp4", "tcp6":
return fmt.Sprintf("%s://%s", na.Protocol, net.JoinHostPort(na.Host, na.Port))
case "unix", "unixpacket":
return fmt.Sprintf("%s://%s", na.Protocol, na.Path)
default:
return na.Raw
}
}
// 验证地址是否有效
func (na *NetworkAddress) Validate() error {
switch na.Protocol {
case "tcp", "tcp4", "tcp6":
if na.Host == "" && na.Port == "" {
return fmt.Errorf("TCP地址需要主机和端口")
}
// 验证端口
if na.Port != "" {
if _, err := net.LookupPort("tcp", na.Port); err != nil {
return fmt.Errorf("无效的端口: %s", na.Port)
}
}
case "unix", "unixpacket":
if na.Path == "" {
return fmt.Errorf("Unix socket路径不能为空")
}
default:
return fmt.Errorf("不支持的协议: %s", na.Protocol)
}
return nil
}

View File

@@ -94,7 +94,11 @@ func (s *ServiceRegister) Close() error {
func (s *ServiceRegister) SetAnonymous(key string, urls []string) { func (s *ServiceRegister) SetAnonymous(key string, urls []string) {
// remove reppeat, clear service all anonymous uri. // remove reppeat, clear service all anonymous uri.
anonymous, _ := s.cli.Get(context.Background(), key) anonymous, err := s.cli.Get(context.Background(), key)
if err != nil {
print.Error("[BSM Register] Get Anonymous Fail: %v", err)
return
}
var as []string var as []string
if len(anonymous.Kvs) > 0 { if len(anonymous.Kvs) > 0 {
@@ -106,7 +110,7 @@ func (s *ServiceRegister) SetAnonymous(key string, urls []string) {
newAnonymous := strings.Join(as, ",") newAnonymous := strings.Join(as, ",")
// put anonymous to etcd // put anonymous to etcd
_, err := s.cli.Put(context.Background(), key, newAnonymous) _, err = s.cli.Put(context.Background(), key, newAnonymous)
if err != nil { if err != nil {
print.Error("[BSM Register] Anonymous Fail.") print.Error("[BSM Register] Anonymous Fail.")

View File

@@ -108,6 +108,14 @@ func (s *Service) Gateway(grpcAddr string, httpAddr string) {
http.ListenAndServe(httpAddr, s.Opts.GatewayMux) http.ListenAndServe(httpAddr, s.Opts.GatewayMux)
} }
func (s *Service) Use(initFunc func() error) {
err := (initFunc)()
if err != nil {
print.Error(err.Error())
panic(err)
}
}
func (s *Service) Stop() { func (s *Service) Stop() {
s.GrpcSrv.GracefulStop() s.GrpcSrv.GracefulStop()
} }

View File

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

View File

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

View File

@@ -11,7 +11,7 @@ import (
func Memory(cli *bigcache.BigCache, opts *bigcache.Config) { func Memory(cli *bigcache.BigCache, opts *bigcache.Config) {
if opts == nil { if opts == nil {
opts = bigcache.Config{ opts = &bigcache.Config{
Shards: 1024, Shards: 1024,
LifeWindow: 10 * time.Minute, LifeWindow: 10 * time.Minute,
CleanWindow: 5 * time.Minute, CleanWindow: 5 * time.Minute,