optmize configure logic and clear conf logic code

pull/74/head
alimy 3 years ago
parent 46d5ef1791
commit 376679a975

@ -63,10 +63,8 @@ clean:
fmt:
@echo Formatting...
@go fmt ./global/...
@go fmt ./internal/...
@go fmt ./pkg/...
@go vet -composites=false ./global/...
@go vet -composites=false ./internal/...
@go vet -composites=false ./pkg/...

@ -14,7 +14,7 @@ Server: # 服务设置
Features:
Default: ["Alipay", "Zinc", "MySQL", "Redis", "MinIO", "LoggerFile"]
Develop: ["Sms", "Zinc", "MySQL", "AliOSS", "LoggerZinc"]
Slim: ["Zinc", "MySQL", "Redis", "MinIO", "LoggerFile"]
Slim: ["Zinc", "MySQL", "Redis", "LocalOSS", "LoggerFile"]
Sms: "SmsJuhe"
SmsJuhe:
Key:

@ -1,11 +0,0 @@
package global
import (
"github.com/go-redis/redis/v8"
"gorm.io/gorm"
)
var (
DBEngine *gorm.DB
Redis *redis.Client
)

@ -1,36 +0,0 @@
package global
import (
"sync"
"github.com/rocboss/paopao-ce/pkg/setting"
"github.com/sirupsen/logrus"
)
var (
Features *setting.FeaturesSettingS
ServerSetting *setting.ServerSettingS
AppSetting *setting.AppSettingS
MySQLSetting *setting.MySQLSettingS
RedisSetting *setting.RedisSettingS
SmsJuheSetting *setting.SmsJuheSettings
AlipaySetting *setting.AlipaySettingS
ZincSetting *setting.ZincSettingS
AliOSSSetting *setting.AliOSSSettingS
MinIOSetting *setting.MinIOSettingS
S3Setting *setting.S3SettingS
LocalOSSSetting *setting.LocalOSSSettingS
JWTSetting *setting.JWTSettingS
LoggerFileSetting *setting.LoggerFileSettingS
LoggerZincSetting *setting.LoggerZincSettingS
Logger *logrus.Logger
Mutex *sync.Mutex
)
func Cfg(key string) (string, bool) {
return Features.Cfg(key)
}
func CfgIf(expression string) bool {
return Features.CfgIf(expression)
}

@ -1,132 +0,0 @@
package main
import (
"flag"
"log"
"strings"
"sync"
"time"
"github.com/go-redis/redis/v8"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/routers/api"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/logger"
"github.com/rocboss/paopao-ce/pkg/setting"
"github.com/rocboss/paopao-ce/pkg/zinc"
)
var (
noDefaultFeatures bool
features suites
)
type suites []string
func (s *suites) String() string {
return strings.Join(*s, ",")
}
func (s *suites) Set(value string) error {
for _, item := range strings.Split(value, ",") {
*s = append(*s, strings.TrimSpace(item))
}
return nil
}
func init() {
flagParse()
err := setupSetting()
if err != nil {
log.Fatalf("init.setupSetting err: %v", err)
}
err = setupLogger()
if err != nil {
log.Fatalf("init.setupLogger err: %v", err)
}
err = setupDBEngine()
if err != nil {
log.Fatalf("init.setupDBEngine err: %v", err)
}
client := zinc.NewClient(global.ZincSetting)
service.Initialize(global.DBEngine, client)
api.Initialize()
}
func setupSetting() error {
setting, err := setting.NewSetting()
if err != nil {
return err
}
global.Features = setting.FeaturesFrom("Features")
if len(features) > 0 {
if err = global.Features.Use(features, noDefaultFeatures); err != nil {
return err
}
}
objects := map[string]interface{}{
"App": &global.AppSetting,
"Server": &global.ServerSetting,
"Alipay": &global.AlipaySetting,
"SmsJuhe": &global.SmsJuheSetting,
"LoggerFile": &global.LoggerFileSetting,
"LoggerZinc": &global.LoggerZincSetting,
"MySQL": &global.MySQLSetting,
"Zinc": &global.ZincSetting,
"Redis": &global.RedisSetting,
"JWT": &global.JWTSetting,
"AliOSS": &global.AliOSSSetting,
"MinIO": &global.MinIOSetting,
"LocalOSS": &global.LocalOSSSetting,
"S3": &global.S3Setting,
}
if err = setting.Unmarshal(objects); err != nil {
return err
}
global.JWTSetting.Expire *= time.Second
global.ServerSetting.ReadTimeout *= time.Second
global.ServerSetting.WriteTimeout *= time.Second
global.Mutex = &sync.Mutex{}
return nil
}
func flagParse() {
flag.BoolVar(&noDefaultFeatures, "no-default-features", false, "whether use default features")
flag.Var(&features, "features", "use special features")
flag.Parse()
}
func setupLogger() error {
logger, err := logger.New()
if err != nil {
return err
}
global.Logger = logger
return nil
}
// setupDBEngine 暂时只支持MySQL
func setupDBEngine() error {
var err error
global.DBEngine, err = model.NewDBEngine(global.MySQLSetting)
if err != nil {
return err
}
global.Redis = redis.NewClient(&redis.Options{
Addr: global.RedisSetting.Host,
Password: global.RedisSetting.Password,
DB: global.RedisSetting.DB,
})
return nil
}

@ -0,0 +1,97 @@
package conf
import (
"log"
"sync"
"time"
"github.com/sirupsen/logrus"
)
var (
loggerFileSetting *LoggerFileSettingS
loggerZincSetting *LoggerZincSettingS
mySQLSetting *MySQLSettingS
redisSetting *RedisSettingS
features *FeaturesSettingS
ServerSetting *ServerSettingS
AppSetting *AppSettingS
SmsJuheSetting *SmsJuheSettings
AlipaySetting *AlipaySettingS
ZincSetting *ZincSettingS
AliOSSSetting *AliOSSSettingS
MinIOSetting *MinIOSettingS
S3Setting *S3SettingS
LocalOSSSetting *LocalOSSSettingS
JWTSetting *JWTSettingS
Logger *logrus.Logger
Mutex *sync.Mutex
)
func setupSetting(suite []string, noDefault bool) error {
setting, err := NewSetting()
if err != nil {
return err
}
features = setting.FeaturesFrom("Features")
if len(suite) > 0 {
if err = features.Use(suite, noDefault); err != nil {
return err
}
}
objects := map[string]interface{}{
"App": &AppSetting,
"Server": &ServerSetting,
"Alipay": &AlipaySetting,
"SmsJuhe": &SmsJuheSetting,
"LoggerFile": &loggerFileSetting,
"LoggerZinc": &loggerZincSetting,
"MySQL": &mySQLSetting,
"Zinc": &ZincSetting,
"Redis": &redisSetting,
"JWT": &JWTSetting,
"AliOSS": &AliOSSSetting,
"MinIO": &MinIOSetting,
"LocalOSS": &LocalOSSSetting,
"S3": &S3Setting,
}
if err = setting.Unmarshal(objects); err != nil {
return err
}
JWTSetting.Expire *= time.Second
ServerSetting.ReadTimeout *= time.Second
ServerSetting.WriteTimeout *= time.Second
Mutex = &sync.Mutex{}
return nil
}
func Initialize(suite []string, noDefault bool) {
err := setupSetting(suite, noDefault)
if err != nil {
log.Fatalf("init.setupSetting err: %v", err)
}
setupLogger()
err = setupDBEngine()
if err != nil {
log.Fatalf("init.setupDBEngine err: %v", err)
}
}
// Cfg get value by key if exist
func Cfg(key string) (string, bool) {
return features.Cfg(key)
}
// CfgIf check expression is true. if expression just have a string like
// `Sms` is mean `Sms` whether define in suite feature settings. expression like
// `Sms = SmsJuhe` is mean whether `Sms` define in suite feature settings and value
// is `SmsJuhe``
func CfgIf(expression string) bool {
return features.CfgIf(expression)
}

@ -0,0 +1,74 @@
package conf
import (
"fmt"
"time"
"github.com/go-redis/redis/v8"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"gorm.io/plugin/dbresolver"
)
var (
DBEngine *gorm.DB
Redis *redis.Client
)
func newDBEngine() (*gorm.DB, error) {
newLogger := logger.New(
Logger, // io writer日志输出的目标前缀和日志包含的内容
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: mySQLSetting.LogLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: false, // 禁用彩色打印
},
)
s := "%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local"
db, err := gorm.Open(mysql.Open(fmt.Sprintf(s,
mySQLSetting.UserName,
mySQLSetting.Password,
mySQLSetting.Host,
mySQLSetting.DBName,
mySQLSetting.Charset,
mySQLSetting.ParseTime,
)), &gorm.Config{
Logger: newLogger,
NamingStrategy: schema.NamingStrategy{
TablePrefix: mySQLSetting.TablePrefix,
SingularTable: true,
},
})
if err != nil {
return nil, err
}
db.Use(dbresolver.Register(dbresolver.Config{}).
SetConnMaxIdleTime(time.Hour).
SetConnMaxLifetime(24 * time.Hour).
SetMaxIdleConns(mySQLSetting.MaxIdleConns).
SetMaxOpenConns(mySQLSetting.MaxOpenConns))
return db, nil
}
// setupDBEngine 暂时只支持MySQL
func setupDBEngine() error {
var err error
DBEngine, err = newDBEngine()
if err != nil {
return err
}
Redis = redis.NewClient(&redis.Options{
Addr: redisSetting.Host,
Password: redisSetting.Password,
DB: redisSetting.DB,
})
return nil
}

@ -0,0 +1,86 @@
package conf
import (
"encoding/json"
"fmt"
"io"
"time"
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/resty.v1"
)
type zincLogIndex struct {
Index map[string]string `json:"index"`
}
type zincLogData struct {
Time time.Time `json:"time"`
Level logrus.Level `json:"level"`
Message string `json:"message"`
Data logrus.Fields `json:"data"`
}
type zincLogHook struct {
host string
index string
user string
password string
}
func (h *zincLogHook) Fire(entry *logrus.Entry) error {
index := &zincLogIndex{
Index: map[string]string{
"_index": h.index,
},
}
indexBytes, _ := json.Marshal(index)
data := &zincLogData{
Time: entry.Time,
Level: entry.Level,
Message: entry.Message,
Data: entry.Data,
}
dataBytes, _ := json.Marshal(data)
logStr := string(indexBytes) + "\n" + string(dataBytes) + "\n"
client := resty.New()
if _, err := client.SetDisableWarn(true).R().
SetHeader("Content-Type", "application/json").
SetBasicAuth(h.user, h.password).
SetBody(logStr).
Post(h.host); err != nil {
fmt.Println(err.Error())
}
return nil
}
func (h *zincLogHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func setupLogger() {
Logger = logrus.New()
Logger.Formatter = &logrus.JSONFormatter{}
if CfgIf("LoggerFile") {
Logger.Out = &lumberjack.Logger{
Filename: loggerFileSetting.SavePath + "/" + loggerFileSetting.FileName + loggerFileSetting.FileExt,
MaxSize: 600,
MaxAge: 10,
LocalTime: true,
}
} else if CfgIf("LoggerZinc") {
Logger.Out = io.Discard
Logger.AddHook(&zincLogHook{
host: loggerZincSetting.Host,
index: loggerZincSetting.Index,
user: loggerZincSetting.User,
password: loggerZincSetting.Password,
})
}
}

@ -1,4 +1,4 @@
package setting
package conf
import (
"testing"

@ -1,4 +1,4 @@
package setting
package conf
import (
"strings"
@ -218,7 +218,7 @@ func (f *FeaturesSettingS) flatFeatures(suite []string) []string {
return features
}
// Cfg get value by key if exsit
// Cfg get value by key if exist
func (f *FeaturesSettingS) Cfg(key string) (string, bool) {
key = strings.ToLower(key)
value, exist := f.features[key]

@ -3,7 +3,7 @@ package dao
import (
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/minio/minio-go/v7"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/zinc"
"gorm.io/gorm"
@ -53,22 +53,22 @@ func NewDataService(engine *gorm.DB, zinc *zinc.ZincClient) core.DataService {
}
func NewObjectStorageService() (oss core.ObjectStorageService) {
if global.CfgIf("AliOSS") {
if conf.CfgIf("AliOSS") {
oss = newAliossServent()
global.Logger.Infoln("use AliOSS as object storage")
} else if global.CfgIf("MinIO") {
conf.Logger.Infoln("use AliOSS as object storage")
} else if conf.CfgIf("MinIO") {
oss = newMinioServeant()
global.Logger.Infoln("use MinIO as object storage")
} else if global.CfgIf("S3") {
conf.Logger.Infoln("use MinIO as object storage")
} else if conf.CfgIf("S3") {
oss = newS3Servent()
global.Logger.Infoln("use S3 as object storage")
} else if global.CfgIf("LocalOSS") {
conf.Logger.Infoln("use S3 as object storage")
} else if conf.CfgIf("LocalOSS") {
oss = newLocalossServent()
global.Logger.Infoln("use LocalOSS as object storage")
conf.Logger.Infoln("use LocalOSS as object storage")
} else {
// default use AliOSS
oss = newAliossServent()
global.Logger.Infoln("use default AliOSS as object storage")
conf.Logger.Infoln("use default AliOSS as object storage")
}
return
}

@ -6,18 +6,18 @@ import (
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
)
func newAliossServent() *aliossServant {
client, err := oss.New(global.AliOSSSetting.Endpoint, global.AliOSSSetting.AccessKeyID, global.AliOSSSetting.AccessKeySecret)
client, err := oss.New(conf.AliOSSSetting.Endpoint, conf.AliOSSSetting.AccessKeyID, conf.AliOSSSetting.AccessKeySecret)
if err != nil {
global.Logger.Fatalf("alioss.New err: %v", err)
conf.Logger.Fatalf("alioss.New err: %v", err)
}
bucket, err := client.Bucket(global.AliOSSSetting.Bucket)
bucket, err := client.Bucket(conf.AliOSSSetting.Bucket)
if err != nil {
global.Logger.Fatalf("client.Bucket err: %v", err)
conf.Logger.Fatalf("client.Bucket err: %v", err)
}
return &aliossServant{
@ -37,19 +37,19 @@ func (s *aliossServant) PutObject(objectKey string, reader io.Reader, objectSize
func (s *aliossServant) SignURL(objectKey string, expiredInSec int64) (string, error) {
signedURL, err := s.bucket.SignURL(objectKey, oss.HTTPGet, expiredInSec)
if err != nil {
global.Logger.Errorf("client.SignURL err: %v", err)
conf.Logger.Errorf("client.SignURL err: %v", err)
return "", err
}
ur, err := url.Parse(signedURL)
if err != nil {
global.Logger.Errorf("url.Parse err: %v", err)
conf.Logger.Errorf("url.Parse err: %v", err)
return "", err
}
epath, err := url.PathUnescape(ur.Path)
if err != nil {
global.Logger.Errorf("url.PathUnescape err: %v", err)
conf.Logger.Errorf("url.PathUnescape err: %v", err)
return "", err
}

@ -9,17 +9,17 @@ import (
"strings"
"time"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
)
func newLocalossServent() *localossServant {
savePath, err := filepath.Abs(global.LocalOSSSetting.SavePath)
savePath, err := filepath.Abs(conf.LocalOSSSetting.SavePath)
if err != nil {
global.Logger.Fatalf("get localOSS save path err: %v", err)
conf.Logger.Fatalf("get localOSS save path err: %v", err)
}
return &localossServant{
savePath: savePath + "/" + global.LocalOSSSetting.Bucket + "/",
savePath: savePath + "/" + conf.LocalOSSSetting.Bucket + "/",
domain: getOssDomain(),
}
}

@ -9,21 +9,21 @@ import (
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
)
func newMinioServeant() *minioServant {
// Initialize minio client object.
client, err := minio.New(global.MinIOSetting.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(global.MinIOSetting.AccessKey, global.MinIOSetting.SecretKey, ""),
Secure: global.MinIOSetting.Secure,
client, err := minio.New(conf.MinIOSetting.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(conf.MinIOSetting.AccessKey, conf.MinIOSetting.SecretKey, ""),
Secure: conf.MinIOSetting.Secure,
})
if err != nil {
global.Logger.Fatalf("minio.New err: %v", err)
conf.Logger.Fatalf("minio.New err: %v", err)
}
return &minioServant{
client: client,
bucket: global.MinIOSetting.Bucket,
bucket: conf.MinIOSetting.Bucket,
domain: getOssDomain(),
}
}
@ -33,7 +33,7 @@ func (s *minioServant) PutObject(objectKey string, reader io.Reader, objectSize
if err != nil {
return "", err
}
global.Logger.Infoln("Successfully uploaded bytes: ", uploadInfo)
conf.Logger.Infoln("Successfully uploaded bytes: ", uploadInfo)
return s.domain + objectKey, nil
}
func (s *minioServant) SignURL(objectKey string, expiredInSec int64) (string, error) {

@ -3,21 +3,21 @@ package dao
import (
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
)
func newS3Servent() *s3Servant {
// Initialize s3 client object use minio-go.
client, err := minio.New(global.S3Setting.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(global.S3Setting.AccessKey, global.S3Setting.SecretKey, ""),
Secure: global.S3Setting.Secure,
client, err := minio.New(conf.S3Setting.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(conf.S3Setting.AccessKey, conf.S3Setting.SecretKey, ""),
Secure: conf.S3Setting.Secure,
})
if err != nil {
global.Logger.Fatalf("s3.New err: %v", err)
conf.Logger.Fatalf("s3.New err: %v", err)
}
return &s3Servant{
client: client,
bucket: global.MinIOSetting.Bucket,
bucket: conf.MinIOSetting.Bucket,
domain: getOssDomain(),
}
}

@ -10,7 +10,7 @@ import (
"strings"
"time"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"gopkg.in/resty.v1"
)
@ -127,9 +127,9 @@ func (d *dataServant) SendPhoneCaptcha(phone string) error {
resp, err := client.R().
SetFormData(map[string]string{
"mobile": phone,
"tpl_id": global.SmsJuheSetting.TplID,
"tpl_value": fmt.Sprintf(global.SmsJuheSetting.TplVal, captcha, m),
"key": global.SmsJuheSetting.Key,
"tpl_id": conf.SmsJuheSetting.TplID,
"tpl_value": fmt.Sprintf(conf.SmsJuheSetting.TplVal, captcha, m),
"key": conf.SmsJuheSetting.Key,
}).Post(gateway)
if err != nil {
return err

@ -1,29 +1,29 @@
package dao
import (
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
)
func getOssDomain() string {
uri := "https://"
if global.CfgIf("AliOSS") {
return uri + global.AliOSSSetting.Domain + "/"
} else if global.CfgIf("MinIO") {
if !global.MinIOSetting.Secure {
if conf.CfgIf("AliOSS") {
return uri + conf.AliOSSSetting.Domain + "/"
} else if conf.CfgIf("MinIO") {
if !conf.MinIOSetting.Secure {
uri = "http://"
}
return uri + global.MinIOSetting.Domain + "/" + global.MinIOSetting.Bucket + "/"
} else if global.CfgIf("S3") {
if !global.S3Setting.Secure {
return uri + conf.MinIOSetting.Domain + "/" + conf.MinIOSetting.Bucket + "/"
} else if conf.CfgIf("S3") {
if !conf.S3Setting.Secure {
uri = "http://"
}
// TODO: will not work well need test in real world
return uri + global.S3Setting.Domain + "/" + global.S3Setting.Bucket + "/"
} else if global.CfgIf("LocalOSS") {
if !global.LocalOSSSetting.Secure {
return uri + conf.S3Setting.Domain + "/" + conf.S3Setting.Bucket + "/"
} else if conf.CfgIf("LocalOSS") {
if !conf.LocalOSSSetting.Secure {
uri = "http://"
}
return uri + global.LocalOSSSetting.Domain + "/oss/" + global.LocalOSSSetting.Bucket + "/"
return uri + conf.LocalOSSSetting.Domain + "/oss/" + conf.LocalOSSSetting.Bucket + "/"
}
return uri + global.AliOSSSetting.Domain + "/"
return uri + conf.AliOSSSetting.Domain + "/"
}

@ -1,7 +1,7 @@
package dao
import (
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"gorm.io/gorm"
)
@ -90,7 +90,7 @@ func (d *dataServant) HandlePostAttachmentBought(post *model.Post, user *model.U
}
// 对附件主新增账单
income := int64(float64(post.AttachmentPrice) * global.AppSetting.AttachmentIncomeRate)
income := int64(float64(post.AttachmentPrice) * conf.AppSetting.AttachmentIncomeRate)
if income > 0 {
master := &model.User{
Model: &model.Model{

@ -0,0 +1,11 @@
package internal
import (
"github.com/rocboss/paopao-ce/internal/routers/api"
"github.com/rocboss/paopao-ce/internal/service"
)
func Initialize() {
service.Initialize()
api.Initialize()
}

@ -5,7 +5,7 @@ import (
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/app"
"github.com/rocboss/paopao-ce/pkg/errcode"
@ -54,11 +54,11 @@ func JWT() gin.HandlerFunc {
ID: claims.UID,
},
}
user, _ = user.Get(global.DBEngine)
user, _ = user.Get(conf.DBEngine)
c.Set("USER", user)
// 强制下线机制
if (global.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer {
if (conf.JWTSetting.Issuer + ":" + user.Salt) != claims.Issuer {
ecode = errcode.UnauthorizedTokenTimeout
}
}

@ -1,20 +1,13 @@
package model
import (
"fmt"
"time"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/pkg/setting"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"gorm.io/plugin/dbresolver"
"gorm.io/plugin/soft_delete"
)
// 公共Model
// Model 公共Model
type Model struct {
ID int64 `gorm:"primary_key" json:"id"`
CreatedOn int64 `json:"created_on"`
@ -25,45 +18,6 @@ type Model struct {
type ConditionsT map[string]interface{}
func NewDBEngine(databaseSetting *setting.MySQLSettingS) (*gorm.DB, error) {
newLogger := logger.New(
global.Logger, // io writer日志输出的目标前缀和日志包含的内容
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: databaseSetting.LogLevel, // 日志级别
IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound记录未找到错误
Colorful: false, // 禁用彩色打印
},
)
s := "%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local"
db, err := gorm.Open(mysql.Open(fmt.Sprintf(s,
databaseSetting.UserName,
databaseSetting.Password,
databaseSetting.Host,
databaseSetting.DBName,
databaseSetting.Charset,
databaseSetting.ParseTime,
)), &gorm.Config{
Logger: newLogger,
NamingStrategy: schema.NamingStrategy{
TablePrefix: databaseSetting.TablePrefix,
SingularTable: true,
},
})
if err != nil {
return nil, err
}
db.Use(dbresolver.Register(dbresolver.Config{}).
SetConnMaxIdleTime(time.Hour).
SetConnMaxLifetime(24 * time.Hour).
SetMaxIdleConns(databaseSetting.MaxIdleConns).
SetMaxOpenConns(databaseSetting.MaxOpenConns))
return db, nil
}
func (m *Model) BeforeCreate(tx *gorm.DB) (err error) {
nowTime := time.Now().Unix()

@ -6,7 +6,7 @@ import (
"github.com/disintegration/imaging"
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/app"
@ -78,7 +78,7 @@ func UploadAttachment(c *gin.Context) {
uploadType := c.Request.FormValue("type")
file, fileHeader, err := c.Request.FormFile("file")
if err != nil {
global.Logger.Errorf("api.UploadAttachment err: %v", err)
conf.Logger.Errorf("api.UploadAttachment err: %v", err)
response.ToErrorResponse(errcode.FileUploadFailed)
return
}
@ -93,7 +93,7 @@ func UploadAttachment(c *gin.Context) {
contentType := fileHeader.Header.Get("Content-Type")
fileExt, err := GetFileExt(fileHeader.Header.Get("Content-Type"))
if err != nil {
global.Logger.Errorf("GetFileExt err: %v", err)
conf.Logger.Errorf("GetFileExt err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
@ -104,7 +104,7 @@ func UploadAttachment(c *gin.Context) {
objectUrl, err := objectStorage.PutObject(ossSavePath, file, fileHeader.Size, contentType)
if err != nil {
global.Logger.Errorf("putObject err: %v", err)
conf.Logger.Errorf("putObject err: %v", err)
response.ToErrorResponse(errcode.FileUploadFailed)
return
}
@ -130,7 +130,7 @@ func UploadAttachment(c *gin.Context) {
attachment, err = service.CreateAttachment(attachment)
if err != nil {
global.Logger.Errorf("service.CreateAttachment err: %v", err)
conf.Logger.Errorf("service.CreateAttachment err: %v", err)
response.ToErrorResponse(errcode.FileUploadFailed)
}
@ -144,7 +144,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) {
// 加载content
content, err := service.GetPostContentByID(contentID)
if err != nil {
global.Logger.Errorf("service.GetPostContentByID err: %v", err)
conf.Logger.Errorf("service.GetPostContentByID err: %v", err)
response.ToErrorResponse(errcode.InvalidDownloadReq)
}
user, _ := c.Get("USER")
@ -152,7 +152,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) {
// 加载post
post, err := service.GetPost(content.PostID)
if err != nil {
global.Logger.Errorf("service.GetPost err: %v", err)
conf.Logger.Errorf("service.GetPost err: %v", err)
response.ToResponse(gin.H{
"paid": false,
})
@ -186,7 +186,7 @@ func DownloadAttachment(c *gin.Context) {
// 加载content
content, err := service.GetPostContentByID(contentID)
if err != nil {
global.Logger.Errorf("service.GetPostContentByID err: %v", err)
conf.Logger.Errorf("service.GetPostContentByID err: %v", err)
response.ToErrorResponse(errcode.InvalidDownloadReq)
}
@ -197,7 +197,7 @@ func DownloadAttachment(c *gin.Context) {
// 加载post
post, err := service.GetPost(content.PostID)
if err != nil {
global.Logger.Errorf("service.GetPost err: %v", err)
conf.Logger.Errorf("service.GetPost err: %v", err)
response.ToResponse(gin.H{
"paid": false,
})
@ -226,7 +226,7 @@ func DownloadAttachment(c *gin.Context) {
AttachmentPrice: post.AttachmentPrice,
}, user.(*model.User))
if err != nil {
global.Logger.Errorf("service.BuyPostAttachment err: %v", err)
conf.Logger.Errorf("service.BuyPostAttachment err: %v", err)
if err == errcode.InsuffientDownloadMoney {
response.ToErrorResponse(errcode.InsuffientDownloadMoney)
@ -242,7 +242,7 @@ func DownloadAttachment(c *gin.Context) {
objectKey := objectStorage.ObjectKey(content.Content)
signedURL, err := objectStorage.SignURL(objectKey, 60)
if err != nil {
global.Logger.Errorf("client.SignURL err: %v", err)
conf.Logger.Errorf("client.SignURL err: %v", err)
response.ToErrorResponse(errcode.DownloadReqError)
return
}

@ -2,7 +2,7 @@ package api
import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/app"
@ -17,7 +17,7 @@ func GetPostComments(c *gin.Context) {
contents, totalRows, err := service.GetPostComments(postID, "id ASC", 0, 0)
if err != nil {
global.Logger.Errorf("service.GetPostComments err: %v\n", err)
conf.Logger.Errorf("service.GetPostComments err: %v\n", err)
response.ToErrorResponse(errcode.GetCommentsFailed)
return
}
@ -30,7 +30,7 @@ func CreatePostComment(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -42,7 +42,7 @@ func CreatePostComment(c *gin.Context) {
if err == errcode.MaxCommentCount {
response.ToErrorResponse(errcode.MaxCommentCount)
} else {
global.Logger.Errorf("service.CreatePostComment err: %v\n", err)
conf.Logger.Errorf("service.CreatePostComment err: %v\n", err)
response.ToErrorResponse(errcode.CreateCommentFailed)
}
return
@ -56,7 +56,7 @@ func DeletePostComment(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -64,7 +64,7 @@ func DeletePostComment(c *gin.Context) {
comment, err := service.GetPostComment(param.ID)
if err != nil {
global.Logger.Errorf("service.GetPostComment err: %v\n", err)
conf.Logger.Errorf("service.GetPostComment err: %v\n", err)
response.ToErrorResponse(errcode.GetCommentFailed)
return
}
@ -77,7 +77,7 @@ func DeletePostComment(c *gin.Context) {
// 执行删除
err = service.DeletePostComment(comment)
if err != nil {
global.Logger.Errorf("service.DeletePostComment err: %v\n", err)
conf.Logger.Errorf("service.DeletePostComment err: %v\n", err)
response.ToErrorResponse(errcode.DeleteCommentFailed)
return
}
@ -90,7 +90,7 @@ func CreatePostCommentReply(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -98,7 +98,7 @@ func CreatePostCommentReply(c *gin.Context) {
comment, err := service.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*model.User).ID, param.AtUserID)
if err != nil {
global.Logger.Errorf("service.CreatePostCommentReply err: %v\n", err)
conf.Logger.Errorf("service.CreatePostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.CreateReplyFailed)
return
}
@ -111,7 +111,7 @@ func DeletePostCommentReply(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -120,7 +120,7 @@ func DeletePostCommentReply(c *gin.Context) {
reply, err := service.GetPostCommentReply(param.ID)
if err != nil {
global.Logger.Errorf("service.GetPostCommentReply err: %v\n", err)
conf.Logger.Errorf("service.GetPostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.GetReplyFailed)
return
}
@ -133,7 +133,7 @@ func DeletePostCommentReply(c *gin.Context) {
// 执行删除
err = service.DeletePostCommentReply(reply)
if err != nil {
global.Logger.Errorf("service.DeletePostCommentReply err: %v\n", err)
conf.Logger.Errorf("service.DeletePostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.DeleteCommentFailed)
return
}

@ -11,7 +11,7 @@ import (
"github.com/afocus/captcha"
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/app"
@ -62,7 +62,7 @@ func GetCaptcha(c *gin.Context) {
key := util.EncodeMD5(uuid.Must(uuid.NewV4()).String())
// 五分钟有效期
global.Redis.SetEX(c, "PaoPaoCaptcha:"+key, password, time.Minute*5)
conf.Redis.SetEX(c, "PaoPaoCaptcha:"+key, password, time.Minute*5)
response := app.NewResponse(c)
response.ToResponse(gin.H{
@ -76,27 +76,27 @@ func PostCaptcha(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
// 验证图片验证码
if res, err := global.Redis.Get(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result(); err != nil || res != param.ImgCaptcha {
if res, err := conf.Redis.Get(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result(); err != nil || res != param.ImgCaptcha {
response.ToErrorResponse(errcode.ErrorCaptchaPassword)
return
}
global.Redis.Del(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result()
conf.Redis.Del(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result()
// 今日频次限制
if res, _ := global.Redis.Get(c.Request.Context(), "PaoPaoSmsCaptcha:"+param.Phone).Result(); convert.StrTo(res).MustInt() >= MAX_PHONE_CAPTCHA {
if res, _ := conf.Redis.Get(c.Request.Context(), "PaoPaoSmsCaptcha:"+param.Phone).Result(); convert.StrTo(res).MustInt() >= MAX_PHONE_CAPTCHA {
response.ToErrorResponse(errcode.TooManyPhoneCaptchaSend)
return
}
err := service.SendPhoneCaptcha(c, param.Phone)
if err != nil {
global.Logger.Errorf("app.SendPhoneCaptcha errs: %v", errs)
conf.Logger.Errorf("app.SendPhoneCaptcha errs: %v", errs)
response.ToErrorResponse(errcode.GetPhoneCaptchaError)
return
}

@ -2,7 +2,7 @@ package api
import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/app"
@ -31,7 +31,7 @@ func GetMessages(c *gin.Context) {
messages, totalRows, err := service.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("service.GetMessages err: %v\n", err)
conf.Logger.Errorf("service.GetMessages err: %v\n", err)
response.ToErrorResponse(errcode.GetMessagesFailed)
return
}
@ -44,7 +44,7 @@ func ReadMessage(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -52,7 +52,7 @@ func ReadMessage(c *gin.Context) {
userID, _ := c.Get("UID")
err := service.ReadMessage(param.ID, userID.(int64))
if err != nil {
global.Logger.Errorf("service.ReadMessage err: %v\n", err)
conf.Logger.Errorf("service.ReadMessage err: %v\n", err)
response.ToErrorResponse(errcode.ReadMessageFailed)
return
}
@ -65,7 +65,7 @@ func SendUserWhisper(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -87,7 +87,7 @@ func SendUserWhisper(c *gin.Context) {
})
if err != nil {
global.Logger.Errorf("service.CreateWhisper err: %v\n", err)
conf.Logger.Errorf("service.CreateWhisper err: %v\n", err)
if err == errcode.TooManyWhisperNum {
response.ToErrorResponse(errcode.TooManyWhisperNum)

@ -2,7 +2,7 @@ package api
import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/service"
@ -32,7 +32,7 @@ func GetPostList(c *gin.Context) {
Limit: app.GetPageSize(c),
})
if err != nil {
global.Logger.Errorf("service.GetPostList err: %v\n", err)
conf.Logger.Errorf("service.GetPostList err: %v\n", err)
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
@ -45,7 +45,7 @@ func GetPostList(c *gin.Context) {
posts, totalRows, err := service.GetPostListFromSearch(q, (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("service.GetPostListFromSearch err: %v\n", err)
conf.Logger.Errorf("service.GetPostListFromSearch err: %v\n", err)
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
@ -60,7 +60,7 @@ func GetPost(c *gin.Context) {
postFormated, err := service.GetPost(postID)
if err != nil {
global.Logger.Errorf("service.GetPost err: %v\n", err)
conf.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -73,7 +73,7 @@ func CreatePost(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -82,7 +82,7 @@ func CreatePost(c *gin.Context) {
post, err := service.CreatePost(c, userID.(int64), param)
if err != nil {
global.Logger.Errorf("service.CreatePost err: %v\n", err)
conf.Logger.Errorf("service.CreatePost err: %v\n", err)
response.ToErrorResponse(errcode.CreatePostFailed)
return
}
@ -95,7 +95,7 @@ func DeletePost(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -105,7 +105,7 @@ func DeletePost(c *gin.Context) {
// 获取Post
postFormated, err := service.GetPost(param.ID)
if err != nil {
global.Logger.Errorf("service.GetPost err: %v\n", err)
conf.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -117,7 +117,7 @@ func DeletePost(c *gin.Context) {
err = service.DeletePost(param.ID)
if err != nil {
global.Logger.Errorf("service.DeletePost err: %v\n", err)
conf.Logger.Errorf("service.DeletePost err: %v\n", err)
response.ToErrorResponse(errcode.DeletePostFailed)
return
}
@ -150,7 +150,7 @@ func PostStar(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -198,7 +198,7 @@ func PostCollection(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -226,7 +226,7 @@ func LockPost(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -236,7 +236,7 @@ func LockPost(c *gin.Context) {
// 获取Post
postFormated, err := service.GetPost(param.ID)
if err != nil {
global.Logger.Errorf("service.GetPost err: %v\n", err)
conf.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -247,7 +247,7 @@ func LockPost(c *gin.Context) {
}
err = service.LockPost(param.ID)
if err != nil {
global.Logger.Errorf("service.LockPost err: %v\n", err)
conf.Logger.Errorf("service.LockPost err: %v\n", err)
response.ToErrorResponse(errcode.LockPostFailed)
return
}
@ -262,7 +262,7 @@ func StickPost(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -272,7 +272,7 @@ func StickPost(c *gin.Context) {
// 获取Post
postFormated, err := service.GetPost(param.ID)
if err != nil {
global.Logger.Errorf("service.GetPost err: %v\n", err)
conf.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -283,7 +283,7 @@ func StickPost(c *gin.Context) {
}
err = service.StickPost(param.ID)
if err != nil {
global.Logger.Errorf("service.StickPost err: %v\n", err)
conf.Logger.Errorf("service.StickPost err: %v\n", err)
response.ToErrorResponse(errcode.LockPostFailed)
return
}
@ -298,14 +298,14 @@ func GetPostTags(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
tags, err := service.GetPostTags(&param)
if err != nil {
global.Logger.Errorf("service.GetPostTags err: %v\n", err)
conf.Logger.Errorf("service.GetPostTags err: %v\n", err)
response.ToErrorResponse(errcode.GetPostTagsFailed)
return

@ -6,7 +6,7 @@ import (
"unicode/utf8"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/app"
@ -21,21 +21,21 @@ func Login(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
user, err := service.DoLogin(c, &param)
if err != nil {
global.Logger.Errorf("service.DoLogin err: %v", err)
conf.Logger.Errorf("service.DoLogin err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
token, err := app.GenerateToken(user)
if err != nil {
global.Logger.Errorf("app.GenerateToken err: %v", err)
conf.Logger.Errorf("app.GenerateToken err: %v", err)
response.ToErrorResponse(errcode.UnauthorizedTokenGenerate)
return
}
@ -52,7 +52,7 @@ func Register(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -60,7 +60,7 @@ func Register(c *gin.Context) {
// 用户名检查
err := service.ValidUsername(param.Username)
if err != nil {
global.Logger.Errorf("service.Register err: %v", err)
conf.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
@ -68,7 +68,7 @@ func Register(c *gin.Context) {
// 密码检查
err = service.CheckPassword(param.Password)
if err != nil {
global.Logger.Errorf("service.Register err: %v", err)
conf.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
@ -79,7 +79,7 @@ func Register(c *gin.Context) {
)
if err != nil {
global.Logger.Errorf("service.Register err: %v", err)
conf.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(errcode.UserRegisterFailed)
return
}
@ -128,7 +128,7 @@ func ChangeUserPassword(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -141,7 +141,7 @@ func ChangeUserPassword(c *gin.Context) {
// 密码检查
err := service.CheckPassword(param.Password)
if err != nil {
global.Logger.Errorf("service.Register err: %v", err)
conf.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
@ -165,7 +165,7 @@ func ChangeNickname(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -193,7 +193,7 @@ func ChangeAvatar(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -221,7 +221,7 @@ func BindUserPhone(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -238,7 +238,7 @@ func BindUserPhone(c *gin.Context) {
}
if err := service.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil {
global.Logger.Errorf("service.CheckPhoneCaptcha err: %v\n", err)
conf.Logger.Errorf("service.CheckPhoneCaptcha err: %v\n", err)
response.ToErrorResponse(err)
return
}
@ -256,7 +256,7 @@ func GetUserProfile(c *gin.Context) {
user, err := service.GetUserByUsername(username)
if err != nil {
global.Logger.Errorf("service.GetUserByUsername err: %v\n", err)
conf.Logger.Errorf("service.GetUserByUsername err: %v\n", err)
response.ToErrorResponse(errcode.NoExistUsername)
return
}
@ -277,7 +277,7 @@ func GetUserPosts(c *gin.Context) {
user, err := service.GetUserByUsername(username)
if err != nil {
global.Logger.Errorf("service.GetUserByUsername err: %v\n", err)
conf.Logger.Errorf("service.GetUserByUsername err: %v\n", err)
response.ToErrorResponse(errcode.NoExistUsername)
return
}
@ -293,7 +293,7 @@ func GetUserPosts(c *gin.Context) {
Limit: app.GetPageSize(c),
})
if err != nil {
global.Logger.Errorf("service.GetPostList err: %v\n", err)
conf.Logger.Errorf("service.GetPostList err: %v\n", err)
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
@ -309,7 +309,7 @@ func GetUserCollections(c *gin.Context) {
posts, totalRows, err := service.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("service.GetUserCollections err: %v\n", err)
conf.Logger.Errorf("service.GetUserCollections err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -323,7 +323,7 @@ func GetUserStars(c *gin.Context) {
userID, _ := c.Get("UID")
posts, totalRows, err := service.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("service.GetUserStars err: %v\n", err)
conf.Logger.Errorf("service.GetUserStars err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -337,7 +337,7 @@ func GetSuggestUsers(c *gin.Context) {
usernames, err := service.GetSuggestUsers(keyword)
if err != nil {
global.Logger.Errorf("service.GetSuggestUsers err: %v\n", err)
conf.Logger.Errorf("service.GetSuggestUsers err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -351,7 +351,7 @@ func GetSuggestTags(c *gin.Context) {
tags, err := service.GetSuggestTags(keyword)
if err != nil {
global.Logger.Errorf("service.GetSuggestTags err: %v\n", err)
conf.Logger.Errorf("service.GetSuggestTags err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -364,7 +364,7 @@ func GetUserRechargeLink(c *gin.Context) {
response := app.NewResponse(c)
valid, errs := app.BindAndValid(c, &param)
if !valid {
global.Logger.Errorf("app.BindAndValid errs: %v", errs)
conf.Logger.Errorf("app.BindAndValid errs: %v", errs)
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
@ -373,37 +373,37 @@ func GetUserRechargeLink(c *gin.Context) {
userID, _ := c.Get("UID")
recharge, err := service.CreateRecharge(userID.(int64), param.Amount)
if err != nil {
global.Logger.Errorf("service.CreateRecharge err: %v\n", err)
conf.Logger.Errorf("service.CreateRecharge err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
client, err := alipay.New(global.AlipaySetting.AppID, global.AlipaySetting.PrivateKey, true)
client, err := alipay.New(conf.AlipaySetting.AppID, conf.AlipaySetting.PrivateKey, true)
// 将 key 的验证调整到初始化阶段
if err != nil {
global.Logger.Errorf("alipay.New err: %v\n", err)
conf.Logger.Errorf("alipay.New err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
err = client.LoadAppPublicCertFromFile("configs/alipayAppCertPublicKey.crt") // 加载应用公钥证书
if err != nil {
global.Logger.Errorf("client.LoadAppPublicCertFromFile err: %v\n", err)
conf.Logger.Errorf("client.LoadAppPublicCertFromFile err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
err = client.LoadAliPayRootCertFromFile("configs/alipayRootCert.crt") // 加载支付宝根证书
if err != nil {
global.Logger.Errorf("client.LoadAliPayRootCertFromFile err: %v\n", err)
conf.Logger.Errorf("client.LoadAliPayRootCertFromFile err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
err = client.LoadAliPayPublicCertFromFile("configs/alipayCertPublicKey_RSA2.crt") // 加载支付宝公钥证书
if err != nil {
global.Logger.Errorf("client.LoadAliPayPublicCertFromFile err: %v\n", err)
conf.Logger.Errorf("client.LoadAliPayPublicCertFromFile err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
@ -416,7 +416,7 @@ func GetUserRechargeLink(c *gin.Context) {
rsp, err := client.TradePreCreate(p)
if err != nil {
global.Logger.Errorf("client.TradePreCreate err: %v\n", err)
conf.Logger.Errorf("client.TradePreCreate err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
@ -458,38 +458,38 @@ func AlipayNotify(c *gin.Context) {
response := app.NewResponse(c)
c.Request.ParseForm()
aliClient, err := alipay.New(global.AlipaySetting.AppID, global.AlipaySetting.PrivateKey, true)
aliClient, err := alipay.New(conf.AlipaySetting.AppID, conf.AlipaySetting.PrivateKey, true)
// 将 key 的验证调整到初始化阶段
if err != nil {
global.Logger.Errorf("alipay.New err: %v\n", err)
conf.Logger.Errorf("alipay.New err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
err = aliClient.LoadAppPublicCertFromFile("configs/alipayAppCertPublicKey.crt") // 加载应用公钥证书
if err != nil {
global.Logger.Errorf("client.LoadAppPublicCertFromFile err: %v\n", err)
conf.Logger.Errorf("client.LoadAppPublicCertFromFile err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
err = aliClient.LoadAliPayRootCertFromFile("configs/alipayRootCert.crt") // 加载支付宝根证书
if err != nil {
global.Logger.Errorf("client.LoadAliPayRootCertFromFile err: %v\n", err)
conf.Logger.Errorf("client.LoadAliPayRootCertFromFile err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
err = aliClient.LoadAliPayPublicCertFromFile("configs/alipayCertPublicKey_RSA2.crt") // 加载支付宝公钥证书
if err != nil {
global.Logger.Errorf("client.LoadAliPayPublicCertFromFile err: %v\n", err)
conf.Logger.Errorf("client.LoadAliPayPublicCertFromFile err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
}
_, err = aliClient.GetTradeNotification(c.Request)
if err != nil {
global.Logger.Errorf("aliClient.GetTradeNotification err: %v\n", err)
global.Logger.Infoln(c.Request.Form)
conf.Logger.Errorf("aliClient.GetTradeNotification err: %v\n", err)
conf.Logger.Infoln(c.Request.Form)
response.ToErrorResponse(errcode.RechargeNotifyError)
return
}
@ -501,7 +501,7 @@ func AlipayNotify(c *gin.Context) {
// 交易支付成功
err = service.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo)
if err != nil {
global.Logger.Errorf("service.FinishRecharge err: %v\n", err)
conf.Logger.Errorf("service.FinishRecharge err: %v\n", err)
response.ToErrorResponse(errcode.RechargeNotifyError)
return
}
@ -516,7 +516,7 @@ func GetUserWalletBills(c *gin.Context) {
bills, totalRows, err := service.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("service.GetUserWalletBills err: %v\n", err)
conf.Logger.Errorf("service.GetUserWalletBills err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}

@ -6,7 +6,7 @@ import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/middleware"
"github.com/rocboss/paopao-ce/internal/routers/api"
)
@ -192,15 +192,15 @@ func NewRouter() *gin.Engine {
// routeLocalOSS register LocalOSS route if neeed
func routeLocalOSS(e *gin.Engine) {
if !global.CfgIf("LocalOSS") {
if !conf.CfgIf("LocalOSS") {
return
}
savePath, err := filepath.Abs(global.LocalOSSSetting.SavePath)
savePath, err := filepath.Abs(conf.LocalOSSSetting.SavePath)
if err != nil {
global.Logger.Fatalf("get localOSS save path err: %v", err)
conf.Logger.Fatalf("get localOSS save path err: %v", err)
}
e.Static("/oss", savePath)
global.Logger.Infof("register LocalOSS route in /oss on save path: %s", savePath)
conf.Logger.Infof("register LocalOSS route in /oss on save path: %s", savePath)
}

@ -4,7 +4,7 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/errcode"
"github.com/rocboss/paopao-ce/pkg/util"
@ -97,7 +97,7 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq)
return nil, err
}
if post.CommentCount >= global.AppSetting.MaxCommentCount {
if post.CommentCount >= conf.AppSetting.MaxCommentCount {
return nil, errcode.MaxCommentCount
}
ip := ctx.ClientIP()
@ -200,7 +200,7 @@ func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post,
return nil, nil, atUserID, err
}
if post.CommentCount >= global.AppSetting.MaxCommentCount {
if post.CommentCount >= conf.AppSetting.MaxCommentCount {
return nil, nil, atUserID, errcode.MaxCommentCount
}

@ -5,7 +5,7 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
@ -27,7 +27,7 @@ func CreateWhisper(c *gin.Context, msg *model.Message) (*model.Message, error) {
whisperKey := fmt.Sprintf("WhisperTimes:%d", msg.SenderUserID)
// 今日频次限制
if res, _ := global.Redis.Get(c, whisperKey).Result(); convert.StrTo(res).MustInt() >= MAX_WHISPER_NUM_DAILY {
if res, _ := conf.Redis.Get(c, whisperKey).Result(); convert.StrTo(res).MustInt() >= MAX_WHISPER_NUM_DAILY {
return nil, errcode.TooManyWhisperNum
}
@ -38,11 +38,11 @@ func CreateWhisper(c *gin.Context, msg *model.Message) (*model.Message, error) {
}
// 写入当日(自然日)计数缓存
global.Redis.Incr(c, whisperKey).Result()
conf.Redis.Incr(c, whisperKey).Result()
currentTime := time.Now()
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
global.Redis.Expire(c, whisperKey, endTime.Sub(currentTime))
conf.Redis.Expire(c, whisperKey, endTime.Sub(currentTime))
return msg, err
}

@ -8,7 +8,7 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/util"
@ -109,7 +109,7 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (*model.Pos
for _, item := range param.Contents {
if err = item.Check(); err != nil {
// 属性非法
global.Logger.Infof("contents check err: %v", err)
conf.Logger.Infof("contents check err: %v", err)
continue
}
@ -378,7 +378,7 @@ func GetPostCount(conditions *model.ConditionsT) (int64, error) {
}
func GetPostListFromSearch(q *core.QueryT, offset, limit int) ([]*model.PostFormated, int64, error) {
queryResult, err := ds.QueryAll(q, global.ZincSetting.Index, offset, limit)
queryResult, err := ds.QueryAll(q, conf.ZincSetting.Index, offset, limit)
if err != nil {
return nil, 0, err
}
@ -392,7 +392,7 @@ func GetPostListFromSearch(q *core.QueryT, offset, limit int) ([]*model.PostForm
}
func GetPostListFromSearchByQuery(query string, offset, limit int) ([]*model.PostFormated, int64, error) {
queryResult, err := ds.QuerySearch(global.ZincSetting.Index, query, offset, limit)
queryResult, err := ds.QuerySearch(conf.ZincSetting.Index, query, offset, limit)
if err != nil {
return nil, 0, err
}
@ -406,7 +406,7 @@ func GetPostListFromSearchByQuery(query string, offset, limit int) ([]*model.Pos
}
func PushPostToSearch(post *model.Post) {
indexName := global.ZincSetting.Index
indexName := conf.ZincSetting.Index
postFormated := post.Format()
postFormated.User = &model.UserFormated{
@ -457,20 +457,20 @@ func PushPostToSearch(post *model.Post) {
}
func DeleteSearchPost(post *model.Post) error {
indexName := global.ZincSetting.Index
indexName := conf.ZincSetting.Index
return ds.DelDoc(indexName, fmt.Sprintf("%d", post.ID))
}
func PushPostsToSearch(c *gin.Context) {
if ok, _ := global.Redis.SetNX(c, "JOB_PUSH_TO_SEARCH", 1, time.Hour).Result(); ok {
if ok, _ := conf.Redis.SetNX(c, "JOB_PUSH_TO_SEARCH", 1, time.Hour).Result(); ok {
splitNum := 1000
totalRows, _ := GetPostCount(&model.ConditionsT{})
pages := math.Ceil(float64(totalRows) / float64(splitNum))
nums := int(pages)
indexName := global.ZincSetting.Index
indexName := conf.ZincSetting.Index
// 创建索引
ds.CreateSearchIndex(indexName)
@ -520,7 +520,7 @@ func PushPostsToSearch(c *gin.Context) {
}
}
global.Redis.Del(c, "JOB_PUSH_TO_SEARCH")
conf.Redis.Del(c, "JOB_PUSH_TO_SEARCH")
}
}
@ -574,8 +574,8 @@ func FormatZincPost(queryResult *zinc.QueryResultT) ([]*model.PostFormated, erro
func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) {
num := param.Num
if num > global.AppSetting.MaxPageSize {
num = global.AppSetting.MaxPageSize
if num > conf.AppSetting.MaxPageSize {
num = conf.AppSetting.MaxPageSize
}
conditions := &model.ConditionsT{}

@ -1,11 +1,10 @@
package service
import (
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/internal/dao"
"github.com/rocboss/paopao-ce/pkg/zinc"
"gorm.io/gorm"
)
var (
@ -14,8 +13,10 @@ var (
DisablePhoneVerify bool
)
func Initialize(engine *gorm.DB, client *zinc.ZincClient) {
ds = dao.NewDataService(engine, client)
func Initialize() {
zincClient := zinc.NewClient(conf.ZincSetting)
ds = dao.NewDataService(conf.DBEngine, zincClient)
attachmentChecker = dao.NewAttachmentCheckerService()
DisablePhoneVerify = !global.CfgIf("Sms")
DisablePhoneVerify = !conf.CfgIf("Sms")
}

@ -4,7 +4,7 @@ import (
"fmt"
"sort"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/pkg/util"
)
@ -23,8 +23,8 @@ func GetParamSign(param map[string]interface{}, secretKey string) string {
signRaw += v
}
if global.ServerSetting.RunMode == "debug" {
global.Logger.Info(map[string]string{
if conf.ServerSetting.RunMode == "debug" {
conf.Logger.Info(map[string]string{
"signRaw": signRaw,
"sysSign": util.EncodeMD5(signRaw + secretKey),
})

@ -9,7 +9,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
@ -63,7 +63,7 @@ func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) {
}
if user.Model != nil && user.ID > 0 {
if errTimes, err := global.Redis.Get(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result(); err == nil {
if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result(); err == nil {
if convert.StrTo(errTimes).MustInt() >= MAX_LOGIN_ERR_TIMES {
return nil, errcode.TooManyLoginError
}
@ -77,14 +77,14 @@ func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) {
}
// 清空登录计数
global.Redis.Del(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID))
conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID))
return user, nil
}
// 登录错误计数
_, err = global.Redis.Incr(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result()
_, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result()
if err == nil {
global.Redis.Expire(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID), time.Hour).Result()
conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID), time.Hour).Result()
}
return nil, errcode.UnauthorizedAuthFailed
@ -332,12 +332,12 @@ func SendPhoneCaptcha(ctx *gin.Context, phone string) error {
}
// 写入计数缓存
global.Redis.Incr(ctx, "PaoPaoSmsCaptcha:"+phone).Result()
conf.Redis.Incr(ctx, "PaoPaoSmsCaptcha:"+phone).Result()
currentTime := time.Now()
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
global.Redis.Expire(ctx, "PaoPaoSmsCaptcha:"+phone, endTime.Sub(currentTime))
conf.Redis.Expire(ctx, "PaoPaoSmsCaptcha:"+phone, endTime.Sub(currentTime))
return nil
}

@ -4,7 +4,7 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/errcode"
)
@ -22,7 +22,7 @@ func CreateRecharge(userID, amount int64) (*model.WalletRecharge, error) {
}
func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error {
if ok, _ := global.Redis.SetNX(ctx, "PaoPaoRecharge:"+tradeNo, 1, time.Second*5).Result(); ok {
if ok, _ := conf.Redis.SetNX(ctx, "PaoPaoRecharge:"+tradeNo, 1, time.Second*5).Result(); ok {
recharge, err := ds.GetRechargeByID(id)
if err != nil {
return err
@ -32,7 +32,7 @@ func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error {
// 标记为已付款
err := ds.HandleRechargeSuccess(recharge, tradeNo)
defer global.Redis.Del(ctx, "PaoPaoRecharge:"+tradeNo)
defer conf.Redis.Del(ctx, "PaoPaoRecharge:"+tradeNo)
if err != nil {
return err

@ -1,35 +1,67 @@
package main
import (
"flag"
"fmt"
"net/http"
"strings"
"github.com/fatih/color"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/routers"
"github.com/rocboss/paopao-ce/pkg/util"
)
var (
version, buildDate, commitID string
noDefaultFeatures bool
features suites
)
type suites []string
func (s *suites) String() string {
return strings.Join(*s, ",")
}
func (s *suites) Set(value string) error {
for _, item := range strings.Split(value, ",") {
*s = append(*s, strings.TrimSpace(item))
}
return nil
}
func init() {
flagParse()
conf.Initialize(features, noDefaultFeatures)
internal.Initialize()
}
func flagParse() {
flag.BoolVar(&noDefaultFeatures, "no-default-features", false, "whether use default features")
flag.Var(&features, "features", "use special features")
flag.Parse()
}
func main() {
gin.SetMode(global.ServerSetting.RunMode)
gin.SetMode(conf.ServerSetting.RunMode)
router := routers.NewRouter()
s := &http.Server{
Addr: global.ServerSetting.HttpIp + ":" + global.ServerSetting.HttpPort,
Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort,
Handler: router,
ReadTimeout: global.ServerSetting.ReadTimeout,
WriteTimeout: global.ServerSetting.WriteTimeout,
ReadTimeout: conf.ServerSetting.ReadTimeout,
WriteTimeout: conf.ServerSetting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
util.PrintHelloBanner(fmt.Sprintf("paopao %s (build:%s %s)", version, commitID, buildDate))
fmt.Fprintf(color.Output, "PaoPao service listen on %s\n",
color.GreenString(fmt.Sprintf("http://%s:%s", global.ServerSetting.HttpIp, global.ServerSetting.HttpPort)),
color.GreenString(fmt.Sprintf("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)),
)
s.ListenAndServe()
}

@ -4,7 +4,7 @@ import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
)
@ -15,18 +15,18 @@ type Claims struct {
}
func GetJWTSecret() []byte {
return []byte(global.JWTSetting.Secret)
return []byte(conf.JWTSetting.Secret)
}
func GenerateToken(User *model.User) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(global.JWTSetting.Expire)
expireTime := nowTime.Add(conf.JWTSetting.Expire)
claims := Claims{
UID: User.ID,
Username: User.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: global.JWTSetting.Issuer + ":" + User.Salt,
Issuer: conf.JWTSetting.Issuer + ":" + User.Salt,
},
}

@ -2,7 +2,7 @@ package app
import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/pkg/convert"
)
@ -18,10 +18,10 @@ func GetPage(c *gin.Context) int {
func GetPageSize(c *gin.Context) int {
pageSize := convert.StrTo(c.Query("page_size")).MustInt()
if pageSize <= 0 {
return global.AppSetting.DefaultPageSize
return conf.AppSetting.DefaultPageSize
}
if pageSize > global.AppSetting.MaxPageSize {
return global.AppSetting.MaxPageSize
if pageSize > conf.AppSetting.MaxPageSize {
return conf.AppSetting.MaxPageSize
}
return pageSize

@ -1,82 +0,0 @@
package logger
import (
"encoding/json"
"fmt"
"io"
"time"
"github.com/rocboss/paopao-ce/global"
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
"gopkg.in/resty.v1"
)
type ZincLogIndex struct {
Index map[string]string `json:"index"`
}
type ZincLogData struct {
Time time.Time `json:"time"`
Level logrus.Level `json:"level"`
Message string `json:"message"`
Data logrus.Fields `json:"data"`
}
type ZincLogHook struct {
Fired bool
}
func (hook *ZincLogHook) Fire(entry *logrus.Entry) error {
index := &ZincLogIndex{
Index: map[string]string{
"_index": global.LoggerZincSetting.Index,
},
}
indexBytes, _ := json.Marshal(index)
data := &ZincLogData{
Time: entry.Time,
Level: entry.Level,
Message: entry.Message,
Data: entry.Data,
}
dataBytes, _ := json.Marshal(data)
logStr := string(indexBytes) + "\n" + string(dataBytes) + "\n"
client := resty.New()
if _, err := client.SetDisableWarn(true).R().
SetHeader("Content-Type", "application/json").
SetBasicAuth(global.LoggerZincSetting.User, global.LoggerZincSetting.Password).
SetBody(logStr).
Post(global.LoggerZincSetting.Host); err != nil {
fmt.Println(err.Error())
}
return nil
}
func (hook *ZincLogHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func New() (*logrus.Logger, error) {
log := logrus.New()
log.Formatter = &logrus.JSONFormatter{}
if global.CfgIf("LoggerFile") {
s := global.LoggerFileSetting
log.Out = &lumberjack.Logger{
Filename: s.SavePath + "/" + s.FileName + s.FileExt,
MaxSize: 600,
MaxAge: 10,
LocalTime: true,
}
} else if global.CfgIf("LoggerZinc") {
log.Out = io.Discard
log.AddHook(&ZincLogHook{})
}
return log, nil
}

@ -8,7 +8,7 @@ import (
"time"
"github.com/go-resty/resty/v2"
"github.com/rocboss/paopao-ce/pkg/setting"
"github.com/rocboss/paopao-ce/internal/conf"
)
type ZincClient struct {
@ -71,7 +71,7 @@ type HitItem struct {
}
// NewClient 获取ZincClient新实例
func NewClient(conf *setting.ZincSettingS) *ZincClient {
func NewClient(conf *conf.ZincSettingS) *ZincClient {
return &ZincClient{
ZincClientConfig: &ZincClientConfig{
ZincHost: conf.Host,

Loading…
Cancel
Save