重构项目结构,将 orm 和 rds 包迁移到 web/globals

This commit is contained in:
2025-05-10 16:59:41 +08:00
parent 37e6e58816
commit d256359681
60 changed files with 363 additions and 349 deletions

View File

@@ -8,7 +8,7 @@ import (
var Alipay *alipay.Client
func InitAlipay() {
func initAlipay() {
var client, err = alipay.New(
env.AlipayAppId,
env.AlipayAppPrivateKey,

View File

@@ -14,7 +14,7 @@ type aliyunClient struct {
Sms *sms.Client
}
func InitAliyun() {
func initAliyun() {
client, err := sms.NewClient(&openapi.Config{
AccessKeyId: &env.AliyunAccessKey,
AccessKeySecret: &env.AliyunAccessKeySecret,

View File

@@ -10,7 +10,6 @@ import (
"net/http/httputil"
"net/url"
"platform/pkg/env"
"platform/pkg/rds"
"strconv"
"strings"
"time"
@@ -36,7 +35,7 @@ type cloud struct {
var Cloud CloudClient
func InitBaiyin() {
func initBaiyin() {
Cloud = &cloud{
url: env.BaiyinAddr,
}
@@ -304,7 +303,7 @@ func (c *cloud) requestCloud(method string, url string, data string) (*http.Resp
func (c *cloud) token(refresh bool) (string, error) {
// redis 获取令牌
if !refresh {
token, err := rds.Client.Get(context.Background(), "remote:token").Result()
token, err := Redis.Get(context.Background(), "remote:token").Result()
if err == nil && token != "" {
return token, nil
}
@@ -347,7 +346,7 @@ func (c *cloud) token(refresh bool) (string, error) {
// redis 设置令牌
token := result["token"].(string)
err = rds.Client.Set(context.Background(), "remote:token", token, 1*time.Hour).Err()
err = Redis.Set(context.Background(), "remote:token", token, 1*time.Hour).Err()
if err != nil {
return "", err
}
@@ -521,6 +520,7 @@ func (c *gateway) GatewayPortActive(param ...PortActiveReq) (map[string]PortData
// endregion
func (c *gateway) requestGateway(method string, url string, data string) (*http.Response, error) {
//goland:noinspection ALL
url = fmt.Sprintf("http://%s:%s@%s:9990%s", c.username, c.password, c.url, url)
req, err := http.NewRequest(method, url, strings.NewReader(data))
if err != nil {

11
web/globals/init.go Normal file
View File

@@ -0,0 +1,11 @@
package globals
func Init() {
initBaiyin()
initAlipay()
initWechatPay()
initAliyun()
initValidator()
initRedis()
initOrm()
}

53
web/globals/orm.go Normal file
View File

@@ -0,0 +1,53 @@
package globals
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"log/slog"
"platform/pkg/env"
)
var DB *gorm.DB
func initOrm() {
// 连接数据库
dsn := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Shanghai",
env.DbHost, env.DbUserName, env.DbPassword, env.DbName, env.DbPort,
)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
TranslateError: true,
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
})
if err != nil {
slog.Error("gorm 初始化数据库失败:", slog.Any("err", err))
panic(err)
}
// 连接池
conn, err := db.DB()
if err != nil {
slog.Error("gorm 初始化数据库失败:", slog.Any("err", err))
panic(err)
}
conn.SetMaxIdleConns(10)
conn.SetMaxOpenConns(100)
DB = db
}
func ExitOrm() error {
if DB != nil {
conn, err := DB.DB()
if err != nil {
return err
}
return conn.Close()
}
return nil
}

16
web/globals/orm/alias.go Normal file
View File

@@ -0,0 +1,16 @@
package orm
import (
"gorm.io/gen"
"gorm.io/gen/field"
)
type WithAlias interface {
Alias() string
}
func Alias(model WithAlias) func(db gen.Dao) gen.Dao {
return func(db gen.Dao) gen.Dao {
return db.Unscoped().Where(field.NewBool(model.Alias(), "deleted_at").IsNull())
}
}

View File

@@ -0,0 +1,85 @@
package orm
import (
"database/sql"
"database/sql/driver"
"time"
)
type LocalDateTime time.Time
var formats = []string{
"2006-01-02 15:04:05.999999999-07:00",
"2006-01-02T15:04:05.999999999-07:00",
"2006-01-02 15:04:05.999999999",
"2006-01-02T15:04:05.999999999",
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02 15:04",
"2006-01-02T15:04",
"2006-01-02",
}
//goland:noinspection GoMixedReceiverTypes
func (ldt *LocalDateTime) Scan(value interface{}) (err error) {
var t time.Time
if strValue, ok := value.(string); ok {
var timeValue time.Time
for _, format := range formats {
timeValue, err = time.Parse(format, strValue)
if err == nil {
t = timeValue
break
}
}
t = timeValue
} else {
nullTime := &sql.NullTime{}
err = nullTime.Scan(value)
if err != nil {
return err
}
if nullTime == nil {
return nil
}
t = nullTime.Time
}
*ldt = LocalDateTime(time.Date(
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.Local,
))
return
}
//goland:noinspection GoMixedReceiverTypes
func (ldt LocalDateTime) Value() (driver.Value, error) {
return time.Time(ldt).Local(), nil
}
// GormDataType gorm common data type
//
//goland:noinspection GoMixedReceiverTy
//goland:noinspection GoMixedReceiverTypes
func (ldt LocalDateTime) GormDataType() string {
return "ldt"
}
//goland:noinspection GoMixedReceiverTypes
func (ldt LocalDateTime) GobEncode() ([]byte, error) {
return time.Time(ldt).GobEncode()
}
//goland:noinspection GoMixedReceiverTypes
func (ldt *LocalDateTime) GobDecode(b []byte) error {
return (*time.Time)(ldt).GobDecode(b)
}
//goland:noinspection GoMixedReceiverTypes
func (ldt LocalDateTime) MarshalJSON() ([]byte, error) {
return time.Time(ldt).MarshalJSON()
}
//goland:noinspection GoMixedReceiverTypes
func (ldt *LocalDateTime) UnmarshalJSON(b []byte) error {
return (*time.Time)(ldt).UnmarshalJSON(b)
}

25
web/globals/redis.go Normal file
View File

@@ -0,0 +1,25 @@
package globals
import (
"net"
"platform/pkg/env"
"github.com/redis/go-redis/v9"
)
var Redis *redis.Client
func initRedis() {
Redis = redis.NewClient(&redis.Options{
Addr: net.JoinHostPort(env.RedisHost, env.RedisPort),
DB: env.RedisDb,
Password: env.RedisPass,
})
}
func ExitRedis() error {
if Redis != nil {
return Redis.Close()
}
return nil
}

View File

@@ -2,23 +2,22 @@ package globals
import (
"errors"
"strings"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
zhtrans "github.com/go-playground/validator/v10/translations/zh"
"github.com/gofiber/fiber/v2"
"strings"
)
var Validator *ValidatorHolder
var Validator *ValidatorClient
type ValidatorHolder struct {
type ValidatorClient struct {
validator *validator.Validate
translator ut.Translator
}
func (v *ValidatorHolder) Validate(c *fiber.Ctx, data any) error {
func (v *ValidatorClient) Validate(c *fiber.Ctx, data any) error {
if err := c.BodyParser(data); err != nil {
return err
@@ -39,7 +38,7 @@ func (v *ValidatorHolder) Validate(c *fiber.Ctx, data any) error {
return nil
}
func InitValidator() {
func initValidator() {
var validate = validator.New(validator.WithRequiredStructEnabled())
var translator = ut.New(zh.New()).GetFallback()
@@ -48,7 +47,7 @@ func InitValidator() {
panic(err)
}
Validator = &ValidatorHolder{
Validator = &ValidatorClient{
validator: validate,
translator: translator,
}

View File

@@ -20,7 +20,7 @@ type WechatPayClient struct {
Notify *notify.Handler
}
func InitWechatPay() {
func initWechatPay() {
// 加载商户私钥
private, err := base64.StdEncoding.DecodeString(env.WechatPayMchPrivateKey)