Compare commits

..

3 Commits

Author SHA1 Message Date
21716c4340 ```
feat(database): 自动迁移表结构并优化数据库初始化函数

将 `AutoMigrate` 逻辑从各数据库初始化方法中提取至统一的 `NewDatabase` 方法内,
避免重复代码。同时修改 `Databases`、`Etcd`、`Memory` 和 `RedisCache` 函数签名,
使其返回实例而非通过参数传递,提高代码可读性和一致性。
```
2025-09-23 16:17:03 +08:00
518c237061 fix(conf): 修改YAML解析方式以支持字符串输入
将yaml.Unmarshal的输入从文件字节流改为直接使用yamlString变量,
确保配置解析能够正确处理字符串格式的YAML内容。
2025-09-23 15:04:14 +08:00
139983134b ```
feat(service): 优化地址解析逻辑以支持端口号直接解析

重构 parseTraditionalStyle 函数,简化 NetworkAddress 构造方式,
并引入 utils.IsNumber 判断纯端口号情况,提升地址解析的准确性与兼容性。
```
2025-09-23 13:26:47 +08:00
8 changed files with 158 additions and 34 deletions

View File

@@ -54,7 +54,7 @@ func New(srvKey string, cfg any) {
}
// 解析YAML
err = yaml.Unmarshal(yamlFile, cfg)
err = yaml.Unmarshal([]byte(yamlString), cfg)
if err != nil {
log.Fatalf("ERROR: %v", err)
}

View File

@@ -34,6 +34,14 @@ func NewDatabase(driver string, dsn []string, options *types.SqlOptions) (db *go
return nil, err
}
// auto migrate table.
if len(MigrateTables) > 0 {
err = db.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return db, nil
}
@@ -74,13 +82,6 @@ func NewMysql(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err err
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return gormDb, nil
}
@@ -119,12 +120,5 @@ func NewPostgres(dsn []string, options *types.SqlOptions) (gormDb *gorm.DB, err
// SetConnMaxLifetime 设置了连接可复用的最大时间。
sqlDB.SetConnMaxLifetime(options.ConnMaxLifetime)
if len(MigrateTables) > 0 {
err = gormDb.AutoMigrate(MigrateTables...)
if err != nil {
return nil, err
}
}
return
}

View File

@@ -5,6 +5,8 @@ import (
"net"
"net/url"
"strings"
"git.apinb.com/bsm-sdk/core/utils"
)
type NetworkAddress struct {
@@ -126,28 +128,24 @@ func determineTCPProtocol(host string) string {
// 解析传统格式如 ":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
return &NetworkAddress{Protocol: "unix", Path: addr}, nil
}
// 否则按 TCP 地址解析
result.Protocol = "tcp"
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("解析地址失败: %w", err)
if err == nil {
return &NetworkAddress{Protocol: "tcp", Host: host, Port: port}, nil
}
result.Host = host
result.Port = port
result.Protocol = determineTCPProtocol(host)
// 检查是否是端口号
if ok := utils.IsNumber(addr); ok {
return &NetworkAddress{Protocol: "tcp", Host: "0.0.0.0", Port: addr}, nil
}
return nil, fmt.Errorf("解析地址失败: %w", err)
return result, nil
}
// 获取网络类型用于 net.Dial 或 net.Listen

129
utils/validator.go Normal file
View File

@@ -0,0 +1,129 @@
package utils
import (
"regexp"
"strings"
"unicode"
)
// IsEmail 验证是否是邮箱格式
func IsEmail(email string) bool {
if strings.TrimSpace(email) == "" {
return false
}
// 邮箱正则表达式
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
matched, err := regexp.MatchString(pattern, email)
if err != nil {
return false
}
return matched
}
// IsMobile 验证是否是手机号(中国手机号格式)
func IsMobile(mobile string) bool {
if strings.TrimSpace(mobile) == "" {
return false
}
// 中国手机号正则表达式1开头第二位3-9后面9位数字
pattern := `^1[3-9]\d{9}$`
matched, err := regexp.MatchString(pattern, mobile)
if err != nil {
return false
}
return matched
}
// IsNumber 验证是否是纯数字
func IsNumber(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if !unicode.IsDigit(char) {
return false
}
}
return true
}
// IsEnglish 验证是否是英文字符(不限大小写)
func IsEnglish(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if !unicode.IsLetter(char) {
return false
}
if !isEnglishLetter(char) {
return false
}
}
return true
}
// IsEnglishWithSpace 验证是否是英文字符(允许空格)
func IsEnglishWithSpace(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if unicode.IsSpace(char) {
continue
}
if !unicode.IsLetter(char) {
return false
}
if !isEnglishLetter(char) {
return false
}
}
return true
}
// IsAlphanumeric 验证是否是字母和数字组合
func IsAlphanumeric(str string) bool {
if strings.TrimSpace(str) == "" {
return false
}
for _, char := range str {
if !unicode.IsLetter(char) && !unicode.IsDigit(char) {
return false
}
}
return true
}
// IsStrongPassword 验证强密码至少8位包含大小写字母和数字
func IsStrongPassword(password string) bool {
if len(password) < 8 {
return false
}
var hasUpper, hasLower, hasDigit bool
for _, char := range password {
switch {
case unicode.IsUpper(char):
hasUpper = true
case unicode.IsLower(char):
hasLower = true
case unicode.IsDigit(char):
hasDigit = true
}
}
return hasUpper && hasLower && hasDigit
}
// 辅助函数:判断是否是英文字母
func isEnglishLetter(char rune) bool {
return (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z')
}

View File

@@ -9,7 +9,7 @@ import (
"gorm.io/gorm"
)
func Databases(cfg *conf.DBConf, db *gorm.DB, opts *types.SqlOptions) {
func Databases(cfg *conf.DBConf, opts *types.SqlOptions) *gorm.DB {
if cfg == nil || len(cfg.Source) == 0 {
panic("No Database Source Found !")
}
@@ -18,10 +18,10 @@ func Databases(cfg *conf.DBConf, db *gorm.DB, opts *types.SqlOptions) {
print.Info("[BSM - %s] Databases: %v", vars.ServiceKey, cfg)
var err error
db, err = database.NewDatabase(cfg.Driver, cfg.Source, opts)
db, err := database.NewDatabase(cfg.Driver, cfg.Source, opts)
if err != nil {
print.Error("Database Init Failed !")
panic(err)
}
return
return db
}

View File

@@ -11,7 +11,7 @@ import (
clientv3 "go.etcd.io/etcd/client/v3"
)
func Etcd(cfg *conf.EtcdConf, cli *clientv3.Client) {
func Etcd(cfg *conf.EtcdConf) (cli *clientv3.Client){
if cfg == nil || len(cfg.Endpoints) == 0 {
return
}

View File

@@ -9,7 +9,7 @@ import (
"github.com/allegro/bigcache/v3"
)
func Memory(cli *bigcache.BigCache, opts *bigcache.Config) {
func Memory(opts *bigcache.Config) (cli *bigcache.BigCache) {
if opts == nil {
opts = &bigcache.Config{
Shards: 1024,
@@ -32,4 +32,5 @@ func Memory(cli *bigcache.BigCache, opts *bigcache.Config) {
}
print.Success("[BSM - %s] Memory Cache: Shards=%d, MaxEntrySize=%d", vars.ServiceKey, opts.Shards, opts.MaxEntrySize)
return
}

View File

@@ -6,11 +6,13 @@ import (
"git.apinb.com/bsm-sdk/core/vars"
)
func RedisCache(cfg string, cli *redis.RedisClient) {
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)
}
return
}