zhangzengfei
2024-12-09 366e2ff546092d9be26411fb698b3ddd8e834a11
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package config
 
import (
    "fmt"
 
    "basic.com/valib/logger.git"
    "github.com/fsnotify/fsnotify"
    "github.com/spf13/viper"
)
 
type mainConfig struct {
    ServePort   int    `mapstructure:"servePort"`
    WorkerNum   int    `mapstructure:"workerNum"`
    MysqlAddr   string `mapstructure:"mysqlAddr"`
    Username    string `mapstructure:"username"`
    Password    string `mapstructure:"password"`
    Database    string `mapstructure:"database"`
    PersonTable string `mapstructure:"personTable"`
}
 
var MainConf = &mainConfig{}
 
type logConfig struct {
    Path       string `mapstructure:"path"`       //日志存储路径
    Level      int    `mapstructure:"level"`      //日志等级
    MaxSize    int    `mapstructure:"maxSize"`    //日志文件大小上限
    MaxBackups int    `mapstructure:"maxBackups"` //日志压缩包个数
    MaxAge     int    `mapstructure:"maxAge"`     //保留压缩包天数
}
 
var LogConf = &logConfig{}
 
func Init() error {
    var err error
    v := viper.New()
    v.SetConfigType("yaml")
    v.SetConfigName("compare")
    v.AddConfigPath("./")
    v.AddConfigPath("./config/")
    v.AddConfigPath("../config/")
    err = v.ReadInConfig()
    if err != nil {
        fmt.Printf("error on parsing configuration file, %s, config file compare.yaml\n", err.Error())
        return err
    }
 
    read2Conf(v)
    v.WatchConfig()
    v.OnConfigChange(func(in fsnotify.Event) {
        read2Conf(v)
    })
 
    return nil
}
 
func read2Conf(v *viper.Viper) {
    v.UnmarshalKey("main", MainConf)
    v.UnmarshalKey("log", LogConf)
 
    logger.SetLevel(LogConf.Level)
 
    if MainConf.WorkerNum == 0 {
        MainConf.WorkerNum = 30
    }
}