🐛 fix: config file loading error

This commit is contained in:
Martial BE 2024-04-18 23:10:47 +08:00
parent 303fe3360b
commit 0c5ad810a9
No known key found for this signature in database
GPG Key ID: D06C32DF0EDB9084
11 changed files with 25 additions and 36 deletions

View File

@ -20,9 +20,9 @@ func InitConf() {
common.SysLog("running in debug mode") common.SysLog("running in debug mode")
} }
common.IsMasterNode = viper.GetString("NODE_TYPE") != "slave" common.IsMasterNode = viper.GetString("node_type") != "slave"
common.RequestInterval = time.Duration(viper.GetInt("POLLING_INTERVAL")) * time.Second common.RequestInterval = time.Duration(viper.GetInt("polling_interval")) * time.Second
common.SessionSecret = common.GetOrDefault("SESSION_SECRET", common.SessionSecret) common.SessionSecret = common.GetOrDefault("session_secret", common.SessionSecret)
} }
func setConfigFile() { func setConfigFile() {

View File

@ -13,13 +13,13 @@ var RedisEnabled = false
// InitRedisClient This function is called after init() // InitRedisClient This function is called after init()
func InitRedisClient() (err error) { func InitRedisClient() (err error) {
redisConn := viper.GetString("REDIS_CONN_STRING") redisConn := viper.GetString("redis_conn_string")
if redisConn == "" { if redisConn == "" {
SysLog("REDIS_CONN_STRING not set, Redis is not enabled") SysLog("REDIS_CONN_STRING not set, Redis is not enabled")
return nil return nil
} }
if viper.GetInt("SYNC_FREQUENCY") == 0 { if viper.GetInt("sync_frequency") == 0 {
SysLog("SYNC_FREQUENCY not set, Redis is disabled") SysLog("SYNC_FREQUENCY not set, Redis is disabled")
return nil return nil
} }
@ -47,7 +47,7 @@ func InitRedisClient() (err error) {
} }
func ParseRedisOption() *redis.Options { func ParseRedisOption() *redis.Options {
opt, err := redis.ParseURL(viper.GetString("REDIS_CONN_STRING")) opt, err := redis.ParseURL(viper.GetString("redis_conn_string"))
if err != nil { if err != nil {
FatalLog("failed to parse Redis connection string: " + err.Error()) FatalLog("failed to parse Redis connection string: " + err.Error())
} }

View File

@ -74,7 +74,7 @@ func InitHttpClient() {
Transport: trans, Transport: trans,
} }
relayTimeout := common.GetOrDefault("RELAY_TIMEOUT", 600) relayTimeout := common.GetOrDefault("connect_timeout", 600)
if relayTimeout != 0 { if relayTimeout != 0 {
HTTPClient.Timeout = time.Duration(relayTimeout) * time.Second HTTPClient.Timeout = time.Duration(relayTimeout) * time.Second
} }

View File

@ -14,7 +14,7 @@ import (
func GetWSClient(proxyAddr string) *websocket.Dialer { func GetWSClient(proxyAddr string) *websocket.Dialer {
dialer := &websocket.Dialer{ dialer := &websocket.Dialer{
HandshakeTimeout: time.Duration(common.GetOrDefault("CONNECT_TIMEOUT", 5)) * time.Second, HandshakeTimeout: time.Duration(common.GetOrDefault("connect_timeout", 5)) * time.Second,
} }
if proxyAddr != "" { if proxyAddr != "" {

View File

@ -53,14 +53,3 @@ func TestImgurUpload(t *testing.T) {
fmt.Println(err) fmt.Println(err)
assert.Nil(t, err) assert.Nil(t, err)
} }
// func TestSMMSUploadError(t *testing.T) {
// InitConfig()
// access_token := viper.GetString("notify.dingtalk.token")
// secret := "test"
// dingTalk := channel.NewDingTalk(access_token, secret)
// err := dingTalk.Send(context.Background(), "Test Title", "*Test Message*")
// fmt.Println(err)
// assert.Error(t, err)
// }

View File

@ -28,7 +28,7 @@ func InitTelegramBot() {
return return
} }
botKey := viper.GetString("TG_BOT_API_KEY") botKey := viper.GetString("tg.bot_api_key")
if botKey == "" { if botKey == "" {
common.SysLog("Telegram bot is not enabled") common.SysLog("Telegram bot is not enabled")
return return
@ -48,7 +48,7 @@ func InitTelegramBot() {
} }
func StartTelegramBot() { func StartTelegramBot() {
botWebhook := viper.GetString("TG_WEBHOOK_SECRET") botWebhook := viper.GetString("tg.webhook_secret")
if botWebhook != "" { if botWebhook != "" {
if common.ServerAddress == "" { if common.ServerAddress == "" {
common.SysLog("Telegram bot is not enabled: Server address is not set") common.SysLog("Telegram bot is not enabled: Server address is not set")
@ -57,7 +57,7 @@ func StartTelegramBot() {
} }
TGWebHookSecret = botWebhook TGWebHookSecret = botWebhook
serverAddress := strings.TrimSuffix(common.ServerAddress, "/") serverAddress := strings.TrimSuffix(common.ServerAddress, "/")
urlPath := fmt.Sprintf("/api/telegram/%s", viper.GetString("TG_BOT_API_KEY")) urlPath := fmt.Sprintf("/api/telegram/%s", viper.GetString("tg.bot_api_key"))
webHookOpts := &ext.AddWebhookOpts{ webHookOpts := &ext.AddWebhookOpts{
SecretToken: TGWebHookSecret, SecretToken: TGWebHookSecret,

10
main.go
View File

@ -57,7 +57,7 @@ func main() {
} }
func initMemoryCache() { func initMemoryCache() {
if viper.GetBool("MEMORY_CACHE_ENABLED") { if viper.GetBool("memory_cache_enabled") {
common.MemoryCacheEnabled = true common.MemoryCacheEnabled = true
} }
@ -65,7 +65,7 @@ func initMemoryCache() {
return return
} }
syncFrequency := viper.GetInt("SYNC_FREQUENCY") syncFrequency := viper.GetInt("sync_frequency")
model.TokenCacheSeconds = syncFrequency model.TokenCacheSeconds = syncFrequency
common.SysLog("memory cache enabled") common.SysLog("memory cache enabled")
@ -74,8 +74,8 @@ func initMemoryCache() {
} }
func initSync() { func initSync() {
go controller.AutomaticallyUpdateChannels(viper.GetInt("CHANNEL_UPDATE_FREQUENCY")) go controller.AutomaticallyUpdateChannels(viper.GetInt("channel.update_frequency"))
go controller.AutomaticallyTestChannels(viper.GetInt("CHANNEL_TEST_FREQUENCY")) go controller.AutomaticallyTestChannels(viper.GetInt("channel.test_frequency"))
} }
func initHttpServer() { func initHttpServer() {
@ -92,7 +92,7 @@ func initHttpServer() {
server.Use(sessions.Sessions("session", store)) server.Use(sessions.Sessions("session", store))
router.SetRouter(server, buildFS, indexPage) router.SetRouter(server, buildFS, indexPage)
port := viper.GetString("PORT") port := viper.GetString("port")
err := server.Run(":" + port) err := server.Run(":" + port)
if err != nil { if err != nil {

View File

@ -103,11 +103,11 @@ func rateLimitFactory(maxRequestNum int, duration int64, mark string) func(c *gi
} }
func GlobalWebRateLimit() func(c *gin.Context) { func GlobalWebRateLimit() func(c *gin.Context) {
return rateLimitFactory(common.GetOrDefault("GLOBAL_WEB_RATE_LIMIT", GlobalWebRateLimitNum), GlobalWebRateLimitDuration, "GW") return rateLimitFactory(common.GetOrDefault("global.web_rate_limit", GlobalWebRateLimitNum), GlobalWebRateLimitDuration, "GW")
} }
func GlobalAPIRateLimit() func(c *gin.Context) { func GlobalAPIRateLimit() func(c *gin.Context) {
return rateLimitFactory(common.GetOrDefault("GLOBAL_API_RATE_LIMIT", GlobalApiRateLimitNum), GlobalApiRateLimitDuration, "GA") return rateLimitFactory(common.GetOrDefault("global.api_rate_limit", GlobalApiRateLimitNum), GlobalApiRateLimitDuration, "GA")
} }
func CriticalRateLimit() func(c *gin.Context) { func CriticalRateLimit() func(c *gin.Context) {

View File

@ -11,7 +11,7 @@ func Telegram() func(c *gin.Context) {
return func(c *gin.Context) { return func(c *gin.Context) {
token := c.Param("token") token := c.Param("token")
if !telegram.TGEnabled || telegram.TGWebHookSecret == "" || token == "" || token != viper.GetString("TG_BOT_API_KEY") { if !telegram.TGEnabled || telegram.TGWebHookSecret == "" || token == "" || token != viper.GetString("tg.bot_api_key") {
c.String(404, "Page not found") c.String(404, "Page not found")
c.Abort() c.Abort()
return return

View File

@ -24,9 +24,9 @@ func SetupDB() {
ChannelGroup.Load() ChannelGroup.Load()
common.RootUserEmail = GetRootUserEmail() common.RootUserEmail = GetRootUserEmail()
if viper.GetBool("BATCH_UPDATE_ENABLED") { if viper.GetBool("batch_update_enabled") {
common.BatchUpdateEnabled = true common.BatchUpdateEnabled = true
common.BatchUpdateInterval = common.GetOrDefault("BATCH_UPDATE_INTERVAL", 5) common.BatchUpdateInterval = common.GetOrDefault("batch_update_interval", 5)
common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s") common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s")
InitBatchUpdater() InitBatchUpdater()
} }
@ -56,8 +56,8 @@ func createRootAccountIfNeed() error {
} }
func chooseDB() (*gorm.DB, error) { func chooseDB() (*gorm.DB, error) {
if viper.IsSet("SQL_DSN") { if viper.IsSet("sql_dsn") {
dsn := viper.GetString("SQL_DSN") dsn := viper.GetString("sql_dsn")
if strings.HasPrefix(dsn, "postgres://") { if strings.HasPrefix(dsn, "postgres://") {
// Use PostgreSQL // Use PostgreSQL
common.SysLog("using PostgreSQL as database") common.SysLog("using PostgreSQL as database")
@ -78,7 +78,7 @@ func chooseDB() (*gorm.DB, error) {
// Use SQLite // Use SQLite
common.SysLog("SQL_DSN not set, using SQLite as database") common.SysLog("SQL_DSN not set, using SQLite as database")
common.UsingSQLite = true common.UsingSQLite = true
config := fmt.Sprintf("?_busy_timeout=%d", common.GetOrDefault("SQLITE_BUSY_TIMEOUT", 3000)) config := fmt.Sprintf("?_busy_timeout=%d", common.GetOrDefault("sqlite_busy_timeout", 3000))
return gorm.Open(sqlite.Open(viper.GetString("sqlite_path")+config), &gorm.Config{ return gorm.Open(sqlite.Open(viper.GetString("sqlite_path")+config), &gorm.Config{
PrepareStmt: true, // precompile SQL PrepareStmt: true, // precompile SQL
}) })

View File

@ -15,7 +15,7 @@ func SetRouter(router *gin.Engine, buildFS embed.FS, indexPage []byte) {
SetApiRouter(router) SetApiRouter(router)
SetDashboardRouter(router) SetDashboardRouter(router)
SetRelayRouter(router) SetRelayRouter(router)
frontendBaseUrl := viper.GetString("FRONTEND_BASE_URL") frontendBaseUrl := viper.GetString("frontend_base_url")
if common.IsMasterNode && frontendBaseUrl != "" { if common.IsMasterNode && frontendBaseUrl != "" {
frontendBaseUrl = "" frontendBaseUrl = ""
common.SysLog("FRONTEND_BASE_URL is ignored on master node") common.SysLog("FRONTEND_BASE_URL is ignored on master node")