Skip to content

Commit 7fe1545

Browse files
committed
新增支持从.env读取配置
1 parent 8abe38c commit 7fe1545

File tree

6 files changed

+115
-50
lines changed

6 files changed

+115
-50
lines changed

.env.example

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
GENERAL_BOT_TOKEN=xxx
2+
GENERAL_LANGUAGE=zh-hans
3+
GENERAL_WORKER_NUM=2
4+
GENERAL_DOWNLOAD_WORKER_NUM=3
5+
GENERAL_ADMIN_UID=0
6+
GENERAL_USER_DAILY_LIMIT=10
7+
GENERAL_PROCESS_WAIT_QUEUE_MAX_SIZE=50
8+
GENERAL_PROCESS_TIMEOUT=60
9+
GENERAL_SUPPORT_TGS_FILE=false
10+
GENERAL_MAX_AMOUNT_PER_REQ=100
11+
12+
COMMUNITY_ENABLE=true
13+
COMMUNITY_FORCE_CHANNEL_SUB=true
14+
COMMUNITY_REWARD_ON_SUB=true
15+
COMMUNITY_CHANNEL_USERNAME=@your_channel
16+
COMMUNITY_REWARD_EXTRA_DOWNLOAD_TIMES=3
17+
18+
CACHE_ENABLED=false
19+
CACHE_STORAGE_DIR=./storage/cache
20+
CACHE_MAX_DISK_USAGE=1024
21+
CACHE_CACHE_EXPIRE=86400
22+
CACHE_CACHE_CLEAN_INTERVAL=1800
23+
24+
LOGGER_REPORT=false
25+
LOGGER_REPORT_URL=
26+
LOGGER_REPORT_QUERY_KEY=
27+
28+
REDIS_SERVER=localhost
29+
REDIS_PORT=6379
30+
REDIS_TLS=false
31+
REDIS_PASSWORD=
32+
REDIS_DB=0

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
/lottie2gif/*
44
/storage/*
55
config.yaml
6+
.env
67
/.idea
78
StickerDownloader
89
*_test.go

config.example.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ general:
1111
max_amount_per_req: 100
1212

1313
community:
14-
enable: true
14+
enable: false
1515
force_channel_sub: true
1616
reward_on_sub: true
1717
channel:

config/config.go

Lines changed: 75 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package config
22

33
import (
4+
"github.com/caarlos0/env/v11"
5+
"github.com/joho/godotenv"
46
"gopkg.in/yaml.v3"
57
"log"
68
"os"
@@ -11,64 +13,80 @@ var cf *Config
1113

1214
type Config struct {
1315
General struct {
14-
BotToken string `yaml:"bot_token"`
15-
Language string `yaml:"language"`
16-
WorkerNum int `yaml:"worker_num"`
17-
DownloadWorkerNum int `yaml:"download_worker_num"`
18-
AdminUID int64 `yaml:"admin_uid"`
19-
UserDailyLimit int `yaml:"user_daily_limit"`
20-
ProcessWaitQueueMaxSize int `yaml:"process_wait_queue_max_size"`
21-
ProcessTimeout int `yaml:"process_timeout"`
22-
SupportTGSFile bool `yaml:"support_tgs_file"`
23-
MaxAmountPerReq int `yaml:"max_amount_per_req"`
24-
} `yaml:"general"`
16+
BotToken string `yaml:"bot_token" env:"BOT_TOKEN,required"`
17+
Language string `yaml:"language" env:"LANGUAGE" envDefault:"zh-hans"`
18+
WorkerNum int `yaml:"worker_num" env:"WORKER_NUM" envDefault:"2"`
19+
DownloadWorkerNum int `yaml:"download_worker_num" env:"DOWNLOAD_WORKER_NUM" envDefault:"3"`
20+
AdminUID int64 `yaml:"admin_uid" env:"ADMIN_UID" envDefault:"0"`
21+
UserDailyLimit int `yaml:"user_daily_limit" env:"USER_DAILY_LIMIT" envDefault:"10"`
22+
ProcessWaitQueueMaxSize int `yaml:"process_wait_queue_max_size" env:"PROCESS_WAIT_QUEUE_MAX_SIZE" envDefault:"50"`
23+
ProcessTimeout int `yaml:"process_timeout" env:"PROCESS_TIMEOUT" envDefault:"60"`
24+
SupportTGSFile bool `yaml:"support_tgs_file" env:"SUPPORT_TGS_FILE" envDefault:"false"`
25+
MaxAmountPerReq int `yaml:"max_amount_per_req" env:"MAX_AMOUNT_PER_REQ" envDefault:"100"`
26+
} `yaml:"general" envPrefix:"GENERAL_"`
27+
2528
Community struct {
26-
Enable bool `yaml:"enable"`
27-
ForceChannelSub bool `yaml:"force_channel_sub"`
28-
RewardOnSub bool `yaml:"reward_on_sub"`
29-
Channel struct {
30-
Username string `yaml:"username"`
31-
} `yaml:"channel"`
29+
Enable bool `yaml:"enable" env:"ENABLE" envDefault:"true"`
30+
ForceChannelSub bool `yaml:"force_channel_sub" env:"FORCE_CHANNEL_SUB" envDefault:"true"`
31+
RewardOnSub bool `yaml:"reward_on_sub" env:"REWARD_ON_SUB" envDefault:"true"`
32+
33+
Channel struct {
34+
Username string `yaml:"username" env:"USERNAME"`
35+
} `yaml:"channel" envPrefix:"CHANNEL_"`
36+
3237
Reward struct {
33-
ExtraDownloadTimes int `yaml:"extra_download_times"`
34-
} `yaml:"reward"`
35-
} `yaml:"community"`
38+
ExtraDownloadTimes int `yaml:"extra_download_times" env:"EXTRA_DOWNLOAD_TIMES" envDefault:"3"`
39+
} `yaml:"reward" envPrefix:"REWARD_"`
40+
} `yaml:"community" envPrefix:"COMMUNITY_"`
41+
3642
Cache struct {
37-
Enabled bool `yaml:"enabled"`
38-
StorageDir string `yaml:"storage_dir"`
39-
MaxDiskUsage int `yaml:"max_disk_usage"`
40-
CacheExpire int `yaml:"cache_expire"`
41-
CacheCleanInterval int `yaml:"cache_clean_interval"`
42-
} `json:"cache"`
43+
Enabled bool `yaml:"enabled" env:"ENABLED" envDefault:"false"`
44+
StorageDir string `yaml:"storage_dir" env:"STORAGE_DIR" envDefault:"./storage/cache"`
45+
MaxDiskUsage int `yaml:"max_disk_usage" env:"MAX_DISK_USAGE" envDefault:"1024"`
46+
CacheExpire int `yaml:"cache_expire" env:"CACHE_EXPIRE" envDefault:"86400"`
47+
CacheCleanInterval int `yaml:"cache_clean_interval" env:"CACHE_CLEAN_INTERVAL" envDefault:"1800"`
48+
} `yaml:"cache" envPrefix:"CACHE_"`
49+
4350
Logger struct {
44-
Report bool `yaml:"report"`
45-
ReportUrl string `yaml:"report_url"`
46-
ReportQueryKey string `yaml:"report_query_key"`
47-
} `yaml:"logger"`
51+
Report bool `yaml:"report" env:"REPORT" envDefault:"false"`
52+
ReportUrl string `yaml:"report_url" env:"REPORT_URL"` // 若遵循 GoLint 可改名为 ReportURL
53+
ReportQueryKey string `yaml:"report_query_key" env:"REPORT_QUERY_KEY"`
54+
} `yaml:"logger" envPrefix:"LOGGER_"`
55+
4856
Redis struct {
49-
Server string `yaml:"server"`
50-
Port string `yaml:"port"`
51-
TLS bool `yaml:"tls"`
52-
Password string `yaml:"password"`
53-
DB int `yaml:"db"`
54-
} `yaml:"redis"`
57+
Server string `yaml:"server" env:"SERVER" envDefault:"localhost"`
58+
Port string `yaml:"port" env:"PORT" envDefault:"6379"`
59+
TLS bool `yaml:"tls" env:"TLS" envDefault:"false"`
60+
Password string `yaml:"password" env:"PASSWORD"`
61+
DB int `yaml:"db" env:"DB" envDefault:"0"`
62+
} `yaml:"redis" envPrefix:"REDIS_"`
5563
}
5664

5765
func Init() {
58-
_, err := os.Stat("./config.yaml")
59-
if err != nil && os.IsNotExist(err) {
60-
log.Fatalln("config.yaml not exist!!")
61-
}
62-
63-
data, err := os.ReadFile("./config.yaml")
64-
if err != nil {
65-
log.Fatalln("failed to load config.yaml", err)
66-
}
66+
if !isExist("./config.yaml") {
67+
if !isExist("./.env") {
68+
log.Fatalln("config.yaml and .env not exist!!")
69+
}
70+
//env
71+
log.Println("Loading configuration from: .env")
72+
_ = godotenv.Load()
73+
cf = new(Config)
74+
if err := env.Parse(cf); err != nil {
75+
log.Fatalln("failed to parse .env", err)
76+
}
77+
} else {
78+
//yaml
79+
log.Println("Loading configuration from: config.yaml")
80+
data, err := os.ReadFile("./config.yaml")
81+
if err != nil {
82+
log.Fatalln("failed to load config.yaml", err)
83+
}
6784

68-
cf = new(Config)
69-
err = yaml.Unmarshal(data, cf)
70-
if err != nil {
71-
log.Fatalln("failed to parse config.yaml", err)
85+
cf = new(Config)
86+
err = yaml.Unmarshal(data, cf)
87+
if err != nil {
88+
log.Fatalln("failed to parse config.yaml", err)
89+
}
7290
}
7391

7492
//validate config
@@ -93,3 +111,11 @@ func Init() {
93111
func Get() *Config {
94112
return cf
95113
}
114+
115+
func isExist(path string) bool {
116+
_, err := os.Stat(path)
117+
if err != nil && os.IsNotExist(err) {
118+
return false
119+
}
120+
return true
121+
}

go.mod

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@ require (
1616

1717
require (
1818
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 // indirect
19+
github.com/caarlos0/env/v11 v11.3.1 // indirect
1920
github.com/cespare/xxhash/v2 v2.2.0 // indirect
2021
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
22+
github.com/joho/godotenv v1.5.1 // indirect
2123
github.com/sirupsen/logrus v1.9.3 // indirect
2224
golang.org/x/sys v0.10.0 // indirect
2325
)

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ github.com/OvyFlash/telegram-bot-api v0.0.0-20250501121306-e13ca08617c9 h1:GUfQn
22
github.com/OvyFlash/telegram-bot-api v0.0.0-20250501121306-e13ca08617c9/go.mod h1:2nRUdsKyWhvezqW/rBGWEQdcTQeTtnbSNd2dgx76WYA=
33
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 h1:MzBOUgng9orim59UnfUTLRjMpd09C5uEVQ6RPGeCaVI=
44
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129/go.mod h1:rFgpPQZYZ8vdbc+48xibu8ALc3yeyd64IhHS+PU6Yyg=
5+
github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=
6+
github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
57
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
68
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
79
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -17,6 +19,8 @@ github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ
1719
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
1820
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
1921
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
22+
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
23+
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
2024
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
2125
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
2226
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=

0 commit comments

Comments
 (0)