core/README.md

513 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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/*
```
## 核心功能模块
### 1. 服务管理 (service)
#### 服务启动与注册
- **Service**: 核心服务结构,支持 gRPC 服务启动和 etcd 注册
- **New()**: 创建服务实例
- **Start()**: 启动服务,支持 etcd 注册和 HTTP 网关
- **Stop()**: 优雅停止服务
- **Use()**: 执行初始化函数
#### 服务发现
- **FoundGrpcMethods()**: 自动发现 gRPC 方法
- **RegisterService()**: 注册服务到 etcd
- **ServiceRegister**: 服务注册器,支持租约管理
#### 元数据解析
- **ParseMetaCtx()**: 解析 gRPC 上下文中的元数据
- **ParseOptions**: 解析选项支持角色验证和私有IP检查
### 2. 配置管理 (conf)
#### 配置加载
- **New()**: 加载配置文件,支持环境变量替换
- **NotNil()**: 验证必需配置项
- **PrintInfo()**: 打印配置信息
- **CheckPort()**: 检查端口配置
#### 配置类型
- **MicroServiceConf**: 微服务配置
- **GatewayConf**: 网关配置
- **DBConf**: 数据库配置
### 3. 加密与解密 (crypto)
#### AES 加密
- **AESGCMEncrypt/AESGCMDecrypt**: GCM 模式加密解密
- **Encrypt/Decrypt**: CBC 模式加密解密
- **AesEncryptECB/AesDecryptECB**: ECB 模式加密解密
- **AesKeyCheck()**: 密钥环境变量检测
#### RSA 加密
- **EncryptWithPublicKey()**: 公钥加密
- **Decrypt()**: 私钥解密
#### 通用加密
- **AesEncryptCBC/AesDecryptCBC**: 通用 CBC 加密解密
- **PKCS7Padding/PKCS7UnPadding**: PKCS7 填充
### 4. 数据库支持 (database)
#### 数据库连接
- **NewDatabase()**: 创建数据库连接,支持 MySQL 和 PostgreSQL
- **NewMysql()**: MySQL 连接
- **NewPostgres()**: PostgreSQL 连接
#### 数据库类型
- **SqlOptions**: 数据库连接选项
- **Std_IICUDS**: 标准数据库模型ID、Identity、Created、Updated、Deleted、Status
- **Std_ICUD**: 标准数据库模型ID、Created、Updated、Deleted
- **Std_Passport**: 护照模型
- **Std_Owner**: 所有者模型
### 5. 缓存支持 (cache)
#### Redis 缓存
- **RedisClient**: Redis 客户端封装
- **New()**: 创建 Redis 连接
- **Hash()**: 哈希分片计算
#### 内存缓存
- 支持内存缓存操作
### 6. 消息队列 (queue)
#### NATS 消息队列
- **Nats**: NATS 客户端封装
- **NewNats()**: 创建 NATS 连接
- **Subscribe()**: 订阅消息
- **Producer()**: 发布消息
### 7. 中间件 (middleware)
#### JWT 认证
- **JwtAuth()**: JWT 认证中间件
- **ParseAuth()**: 解析认证信息
#### CORS 支持
- **Cors()**: CORS 中间件
#### 运行模式
- **Mode()**: 设置 Gin 运行模式
### 8. 工具类 (utils)
#### 网络工具 (net.go) ✨ 新增超时功能
完整的网络工具集所有HTTP请求都支持超时控制。
**IP地址工具**
- **IsPublicIP(ipString)**: 判断是否为公网IP
- 识别私有网段10.x.x.x、172.16-31.x.x、192.168.x.x
- 识别回环地址和链路本地地址
- 性能62.55 ns/op零内存分配
- **GetLocationIP()**: 获取本机第一个有效IPv4地址
- 自动跳过回环和链路本地地址
- 返回 "127.0.0.1" 如果找不到
- **LocalIPv4s()**: 获取本机所有IPv4地址列表
- 返回所有非回环IPv4地址
- 自动过滤链路本地地址
- **GetOutBoundIP()**: 获取外网IP地址
**HTTP请求工具带超时保护**
- **HttpGet(url, timeout...)**: HTTP GET请求
- 默认超时30秒
- 支持自定义超时
- Context超时控制
- 示例:`body, _ := HttpGet("https://api.com", 5*time.Second)`
- **HttpPost(url, headers, data, timeout...)**: HTTP POST请求
- 默认超时30秒
- 自动设置Content-Type和Request-Id
- 检查HTTP状态码
- 示例:`body, _ := HttpPost(url, headers, data, 10*time.Second)`
- **HttpPostJSON(url, headers, data)**: HTTP POST JSON请求
- 自动JSON序列化
- 继承HttpPost所有特性
- 示例:`body, _ := HttpPostJSON(url, map[string]any{"key": "value"})`
- **HttpRequest(request, timeout...)**: 执行自定义HTTP请求
- 支持任何HTTP方法
- 完全自定义请求
- **DownloadFile(url, savePath, progressCallback, timeout...)**: 文件下载
- 默认超时5分钟
- 实时进度回调
- 文件权限0644
- 缓冲区大小32KB
- 示例:
```go
progress := func(total, downloaded int64) {
percent := float64(downloaded) / float64(total) * 100
fmt.Printf("下载: %.2f%%\n", percent)
}
err := DownloadFile(url, "file.zip", progress, 10*time.Minute)
```
**配置常量:**
- `DefaultHTTPTimeout`: 30秒HTTP请求默认超时
- `DefaultDownloadTimeout`: 5分钟下载默认超时
- `DefaultBufferSize`: 32KB默认缓冲区
#### 二维码生成 (qrcode.go) 🎨 全新功能
完整的二维码生成工具,支持多种输出格式和自定义配置。
**基础生成:**
- **GenerateQRCode(content, filename, size...)**: 生成二维码文件
- 默认尺寸256x256
- 支持自定义尺寸21-8192像素
- 中级纠错15%容错)
- 示例:`GenerateQRCode("https://example.com", "qr.png", 512)`
- **GenerateQRCodeBytes(content, size...)**: 生成字节数组
- PNG格式
- 适合HTTP响应、数据库存储
- 性能:~1.5ms/次
- 示例:`bytes, _ := GenerateQRCodeBytes("内容", 300)`
- **GenerateQRCodeBase64(content, size...)**: 生成Base64编码
- 便于JSON传输
- 适合数据库文本字段
- 示例:`base64Str, _ := GenerateQRCodeBase64("内容")`
- **GenerateQRCodeDataURL(content, size...)**: 生成Data URL
- 可直接用于HTML <img>标签
- 包含完整图片数据
- 示例:`dataURL, _ := GenerateQRCodeDataURL("内容")`
**高级功能:**
- **GenerateQRCodeWithConfig(content, config)**: 自定义配置生成
- 自定义尺寸、颜色、纠错级别
- 示例:
```go
config := &QRCodeConfig{
Size: 512,
ErrorLevel: QRCodeErrorLevelHigh,
ForegroundColor: color.RGBA{255, 0, 0, 255}, // 红色
BackgroundColor: color.White,
}
bytes, _ := GenerateQRCodeWithConfig("内容", config)
```
- **GenerateQRCodeWithLogo(content, logoPath, size...)**: 带Logo二维码
- Logo占据中心1/5区域
- 高级纠错30%容错)
- 建议尺寸>=512
- 示例:`bytes, _ := GenerateQRCodeWithLogo("内容", "logo.png", 512)`
- **BatchGenerateQRCode(items, size...)**: 批量生成
- 一次生成多个二维码
- 返回失败列表
- 示例:
```go
items := map[string]string{
"产品A": "qr_a.png",
"产品B": "qr_b.png",
}
failed, _ := BatchGenerateQRCode(items, 300)
```
**纠错级别:**
- `QRCodeErrorLevelLow`: 低级纠错(~7%容错)
- `QRCodeErrorLevelMedium`: 中级纠错(~15%容错,默认)
- `QRCodeErrorLevelQuartile`: 较高级纠错(~25%容错)
- `QRCodeErrorLevelHigh`: 高级纠错(~30%容错适合Logo
**实用场景:**
- URL分享、名片vCard、WiFi连接
- 支付码、位置信息、文本分享
- 产品标签、会员卡、门票优惠券
**性能指标:**
- 生成速度1.5-2.2 ms/次
- 内存占用:~984 KB/次
- 并发安全:所有函数都是并发安全的
#### 数据类型转换
- **String2Int/String2Int64**: 字符串转整数
- **String2Float64/String2Float32**: 字符串转浮点数
- **Int2String/Int642String**: 整数转字符串
- **Float64ToString/Float32ToString**: 浮点数转字符串
- **AnyToString()**: 任意类型转字符串
#### 时间处理
- **Time2String()**: 时间转字符串
- **String2Time()**: 字符串转时间
#### 身份标识
- **UUID()**: 生成 UUID
- **ULID()**: 生成 ULID
#### 文件操作
- **PathExists()**: 检查路径是否存在
- **CreateDir()**: 创建目录
- **GetRunPath()**: 获取运行路径
- **GetCurrentPath()**: 获取当前路径
#### JSON 处理
- **JsonEscape()**: JSON 转义
### 9. 错误处理 (errcode)
#### 标准错误码
- **Header 错误**: 101-104
- **标准错误**: 110-121
- **JWT 错误**: 131-139
- **模型错误**: 151-157
- **gRPC 错误**: 171-186
#### 错误创建
- **NewError()**: 创建标准错误
- **ErrFatal()**: 创建致命错误
- **ErrNotFound()**: 创建未找到错误
### 10. 响应处理 (infra)
#### 统一响应
- **Reply**: 统一响应结构
- **Success()**: 成功响应
- **Error()**: 错误响应,支持 gRPC 状态码转换
### 11. 日志打印 (printer)
#### 彩色日志
- **Info()**: 信息日志(白色)
- **Warn()**: 警告日志(橙色)
- **Success()**: 成功日志(绿色)
- **Error()**: 错误日志(红色)
- **Json()**: JSON 格式化输出
### 12. 环境管理 (env)
#### 运行时环境
- **RuntimeEnv**: 运行时环境配置
- **NewEnv()**: 初始化环境
- **GetEnvDefault()**: 获取环境变量默认值
### 13. 变量管理 (vars)
#### 全局变量
- **ServiceKey**: 服务键
- **HostName**: 主机名
- **VERSION**: 版本号
- **BUILD_TIME**: 构建时间
- **GO_VERSION**: Go 版本
### 14. 第三方集成 (third)
#### 微信集成
- 支持微信相关功能
### 15. 许可证管理 (licence)
#### 许可证验证
- 支持许可证文件验证
### 配置环境变量
```bash
export BSM_Workspace=def
export BSM_JwtSecretKey=your_secret_key
export BSM_RuntimeMode=dev
export BSM_Prefix=/usr/local/bsm
```
### 安全建议
- 使用强密钥进行加密
- 定期更新 JWT 密钥
- 配置适当的数据库连接池
- 使用 HTTPS 进行通信
- 定期检查许可证有效性
## 🚀 快速开始
### 网络工具示例
```go
package main
import (
"fmt"
"time"
"git.apinb.com/bsm-sdk/core/utils"
)
func main() {
// 1. 获取本机IP
localIP := utils.GetLocationIP()
fmt.Printf("本机IP: %s\n", localIP)
// 2. HTTP GET请求带超时
body, err := utils.HttpGet("https://api.example.com/data", 5*time.Second)
if err != nil {
fmt.Printf("请求失败: %v\n", err)
return
}
fmt.Printf("响应: %s\n", string(body))
// 3. POST JSON数据
headers := map[string]string{"Authorization": "Bearer token"}
data := map[string]any{"name": "张三", "age": 25}
body, err = utils.HttpPostJSON("https://api.example.com/users", headers, data)
// 4. 下载文件(带进度)
progress := func(total, downloaded int64) {
if total > 0 {
percent := float64(downloaded) / float64(total) * 100
fmt.Printf("\r下载进度: %.2f%%", percent)
}
}
err = utils.DownloadFile(
"https://example.com/file.zip",
"./download/file.zip",
progress,
10*time.Minute,
)
}
```
### 二维码生成示例
```go
package main
import (
"fmt"
"image/color"
"git.apinb.com/bsm-sdk/core/utils"
)
func main() {
// 1. 基础二维码
err := utils.GenerateQRCode("https://example.com", "qrcode.png")
// 2. 自定义尺寸
err = utils.GenerateQRCode("内容", "qrcode_large.png", 512)
// 3. 生成Base64用于API响应
base64Str, _ := utils.GenerateQRCodeBase64("订单号20231103001")
fmt.Printf("Base64: %s\n", base64Str)
// 4. 自定义颜色
config := &utils.QRCodeConfig{
Size: 512,
ErrorLevel: utils.QRCodeErrorLevelHigh,
ForegroundColor: color.RGBA{255, 0, 0, 255}, // 红色
BackgroundColor: color.White,
}
bytes, _ := utils.GenerateQRCodeWithConfig("内容", config)
utils.SaveQRCodeBytes(bytes, "red_qrcode.png")
// 5. 批量生成
items := map[string]string{
"产品A": "qr_a.png",
"产品B": "qr_b.png",
"产品C": "qr_c.png",
}
failed, err := utils.BatchGenerateQRCode(items, 300)
if err != nil {
fmt.Printf("部分失败: %v\n", failed)
}
// 6. 名片二维码vCard
vcard := `BEGIN:VCARD
VERSION:3.0
FN:张三
TEL:+86-138-0000-0000
EMAIL:zhangsan@example.com
ORG:某某公司
END:VCARD`
utils.GenerateQRCode(vcard, "namecard.png", 400)
// 7. WiFi连接二维码
wifiInfo := "WIFI:T:WPA;S:MyWiFi;P:password123;;"
utils.GenerateQRCode(wifiInfo, "wifi_qr.png", 300)
}
```
## 📝 使用建议
### 1. 配置管理
```go
// 推荐使用环境变量进行配置
conf.New("your-service", &config)
```
### 2. 错误处理
```go
// 使用统一的错误码
if err != nil {
return errcode.ErrInternal
}
// 网络请求错误处理
body, err := utils.HttpGet(url, 5*time.Second)
if err != nil {
// 判断是否为超时错误
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("请求超时")
}
return err
}
```
### 3. 缓存使用
```go
// 使用统一的缓存键前缀
key := redisClient.BuildKey("user", userID)
```
### 4. 数据库连接
```go
// 使用连接池优化
db, err := database.NewDatabase("mysql", dsn, options)
```
### 5. 二维码生成最佳实践
```go
// 内容较长时增大尺寸
if len(content) > 100 {
size = 512
} else {
size = 256
}
// 添加Logo时使用高级纠错
config := &utils.QRCodeConfig{
Size: 512,
ErrorLevel: utils.QRCodeErrorLevelHigh, // 重要!
ForegroundColor: color.Black,
BackgroundColor: color.White,
}
```
## 许可证
本项目采用私有许可证,请确保已获得相应的使用授权。
## 贡献
欢迎提交 Issue 和 Pull Request 来改进本项目。
## 联系方式
如有问题,请联系开发团队。