From 130051cd86cef2d5d6b28355cad8d12f5cc15d22 Mon Sep 17 00:00:00 2001 From: RockChinQ <1010553892@qq.com> Date: Mon, 2 Sep 2024 19:17:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E9=80=9A=E8=BF=87?= =?UTF-8?q?=E7=8E=AF=E5=A2=83=E5=8F=98=E9=87=8F=E4=BF=AE=E6=94=B9=E9=85=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/config/config.go | 47 +++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/backend/config/config.go b/backend/config/config.go index 98e4849..2d9b658 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -1,6 +1,9 @@ package config import ( + "strconv" + "strings" + "github.com/spf13/viper" "github.com/google/uuid" @@ -70,19 +73,53 @@ func NewConfig() (*Config, bool, error) { viper.SetConfigType("yaml") viper.AddConfigPath("./data/") + // 应用环境变量 + viper.AutomaticEnv() + + replacer := strings.NewReplacer(".", "__") + + viper.SetEnvKeyReplacer(replacer) + if err := viper.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { // 设置默认配置 SetInitValue() - // Config file not found; write default config - if err := WriteConfig(); err != nil { - return nil, false, err - } - return nil, true, nil } else { return nil, false, err } } + postOperation() + + // Config file not found; write default config + if err := WriteConfig(); err != nil { + return nil, false, err + } + return &Config{}, false, nil } + +func postOperation() { + bots := viper.Get("service.bots") + switch bots := bots.(type) { // 修改此行 + case []interface{}: + // 检查是否为[]int + for _, v := range bots { // 修改此行 + if _, ok := v.(int); !ok { + return + } + } + case string: + botsStr := bots // 修改此行 + botsArr := strings.Split(botsStr, ",") + var botsInt []int + for _, bot := range botsArr { + botInt, err := strconv.Atoi(strings.TrimSpace(bot)) + if err != nil { + return + } + botsInt = append(botsInt, botInt) + } + viper.Set("service.bots", botsInt) + } +}