Skip to content

Commit 8e43a15

Browse files
committed
conf
1 parent 1326424 commit 8e43a15

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

conf/config-sample.yaml

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
log:
2+
Level: info
3+
4+
# base config for convert
5+
convert:
6+
source: "/etc/openclash/rule_provider"
7+
target: "/etc/mosdns/from_provider"
8+
processFiles:
9+
- "ai.txt"
10+
- "apple.yaml"
11+
- "direct.yaml"
12+
- "gfw.yaml"
13+
- "icloud.yaml"
14+
- "proxy.yaml"
15+
16+
# run background to watch the file change
17+
service:
18+
enable: True
19+
dbFile: "/etc/mosdns/provider2domainset.db"

conf/config.go

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package conf
2+
3+
import (
4+
_ "embed"
5+
"os"
6+
7+
"github.com/dn-11/provider2domainset/log"
8+
"github.com/spf13/viper"
9+
"go.uber.org/zap/zapcore"
10+
)
11+
12+
//go:embed config-sample.yaml
13+
var configSample []byte
14+
15+
var Convert struct {
16+
Source string
17+
Target string
18+
ProcessFiles []string
19+
}
20+
21+
var Service struct {
22+
Enable bool
23+
DbFile string
24+
}
25+
26+
var Log struct {
27+
Level zapcore.Level
28+
}
29+
30+
func Init(file string) {
31+
if _, err := os.Stat(file); err != nil {
32+
if !os.IsNotExist(err) {
33+
log.Logger.Sugar().With(err).Errorf("get stat of %s failed", file)
34+
}
35+
log.Logger.Sugar().Infof("config not existed, creating at %s", file)
36+
created, err := os.Create(file)
37+
if err != nil {
38+
log.Logger.Sugar().With(err).Errorf("create config at %s failed", file)
39+
}
40+
if _, err := created.Write(configSample); err != nil {
41+
log.Logger.Sugar().With(err).Errorf("write config at %s failed", file)
42+
}
43+
}
44+
45+
viper.SetConfigFile(file)
46+
err := viper.ReadInConfig()
47+
48+
update()
49+
if err != nil {
50+
log.Logger.Sugar().With(err).Errorf("read config from %s failed", file)
51+
}
52+
}
53+
54+
func update() {
55+
Convert.Source = viper.GetString("convert.source")
56+
Convert.Target = viper.GetString("convert.target")
57+
Convert.ProcessFiles = viper.GetStringSlice("convert.process_files")
58+
59+
Service.Enable = viper.GetBool("service.enable")
60+
Service.DbFile = viper.GetString("service.db_file")
61+
62+
if level, err := zapcore.ParseLevel(viper.GetString("log.level")); err == nil {
63+
Log.Level = level
64+
}
65+
}

conf/config_test.go

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package conf
2+
3+
import "testing"
4+
5+
func TestParseConfig(t *testing.T) {
6+
Init("config-sample.yaml")
7+
}

0 commit comments

Comments
 (0)