// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package config import ( "fmt" "path/filepath" "strings" "github.com/spf13/viper" ) type LogConfig struct { Path string Level string MaxSize int MaxBackups int MaxAge int Stacktrace bool } type MysqlConfig struct { User string Password string Addr string DB string Charset string MaxIdle int MaxConn int LogMode bool } type RedisConfig struct { Addrs []string Password string DB int PoolSize int MinIdleConns int MaxRetries int Cluster bool } type ElasticConfig struct { Addrs []string Sniff bool } type ThirdPartNode struct { Host string AppKey string AppSecret string } type AliPartNode struct { AesKey string } type ThirdPartyConfig struct { Ali AliPartNode } type RPCNode struct { ServiceName string ServicePort int ServiceIp string MysqlDb string RedisDb int LogLevel string LogStacktrace bool } type KeepaliveConfig struct { ClientTime int ClientTimeout int ServerTime int ServerTimeout int ServerMiniTime int } type OssConfig struct { BrandImage string SeriesImage string AccessKeyId string AccessKeySecret string Endpoint string Bucket string AvatarBucket string IconBucket string } type Coupon struct { Url string Action string ExpireDate string } type RPCConfig struct { Keepalive KeepaliveConfig Common RPCNode } type Configure struct { // 视频间隔 VideoInterval int // 课程 Courses []string // 并发数 Channel int // 做题课程 QuizCourses []string // 是否全部网页需要打开 IsOpenAll bool OnlyVisit bool VisitCount int } var Conf *Configure var v *viper.Viper // LoadConfig 装载配置文件 func LoadConfig(filename string) error { configPath, configName := filepath.Split(filename) fileList := strings.Split(configName, ".") if len(fileList) < 2 { return fmt.Errorf("%s", "文件格式不正确") } configName = fileList[0] fileExt := fileList[1] var err error if fileExt == "json" { err = LoadConfigFromJson(configName, configPath) } else if fileExt == "yaml" || fileExt == "yml" { err = LoadConfigFromYaml(configName, configPath) } else { err = fmt.Errorf("%s", "不支持的文件格式") } // 出错直接返回 if err != nil { return err } return nil } // LoadConfigFromYaml 装载yaml类型的配置文件 func LoadConfigFromYaml(configName, configPath string) error { v = viper.New() v.SetConfigName(configName) v.AddConfigPath(configPath) //设置配置文件类型 v.SetConfigType("yaml") if err := v.ReadInConfig(); err != nil { return err } return parseConfig() } // LoadConfigFromJson 装载json类型的配置文件 func LoadConfigFromJson(configName, configPath string) error { v = viper.New() v.SetConfigName(configName) v.AddConfigPath(configPath) //设置配置文件类型 v.SetConfigType("json") if err := v.ReadInConfig(); err != nil { return err } return parseConfig() } func parseConfig() error { Conf = &Configure{} if err := v.Unmarshal(Conf); err != nil { return err } return nil }