github.com/OrigamiWang/msd/micro@v0.0.0-20240229032328-b62246268db9/confparser/conf.go (about)

     1  package confparser
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"reflect"
     7  	"strings"
     8  	"time"
     9  
    10  	logutil "github.com/OrigamiWang/msd/micro/util/log"
    11  	"gopkg.in/yaml.v3"
    12  )
    13  
    14  var Conf *Config // 读取配置文件的配置
    15  
    16  type Database struct {
    17  	Key      string                 `yaml:"key"`  // 存储在dbConn map[interface{}]int 中使用的key
    18  	Type     string                 `yaml:"type"` // 数据库类型:MySQL、mongodb、redis
    19  	Name     string                 `yaml:"name"`
    20  	Host     string                 `yaml:"host"`
    21  	Port     int                    `yaml:"port"`
    22  	User     string                 `yaml:"user"`
    23  	Password string                 `yaml:"password"`
    24  	EXT      map[string]interface{} `yaml:",flow"` // 扩展
    25  }
    26  
    27  type Config struct {
    28  	Dbs []Database             `yaml:"databases,flow"`
    29  	EXT map[string]interface{} `yaml:"ext,flow"`
    30  }
    31  
    32  func init() {
    33  	// automately load local conf
    34  	logutil.Info("load conf...")
    35  	Conf = LoadConf()
    36  }
    37  
    38  func LoadConf() *Config {
    39  	fileName := "conf.yml"
    40  	if _, err := os.Stat(fileName); err != nil {
    41  		logutil.Warn("config file not exist, fileName: %v", fileName)
    42  		return nil
    43  	}
    44  	dataBytes, err := os.ReadFile("conf.yml")
    45  	if err != nil {
    46  		logutil.Error("load conf failed, err: %v", err)
    47  		return nil
    48  	}
    49  	config := &Config{}
    50  	err = yaml.Unmarshal(dataBytes, config)
    51  	if err != nil {
    52  		logutil.Error("unmarshal config failed, err: %v", err)
    53  		return nil
    54  	}
    55  	return config
    56  }
    57  
    58  func (c *Config) Ext(keys string, defaultVal ...interface{}) interface{} {
    59  	res, err := c.ExtSep(keys, ".")
    60  	if err != nil || res == nil {
    61  		if len(defaultVal) > 0 {
    62  			return defaultVal[0]
    63  		} else {
    64  			panic(err)
    65  		}
    66  	}
    67  	return res
    68  }
    69  
    70  func (c *Config) ExtSep(keys, sep string) (interface{}, error) {
    71  	ks := strings.Split(keys, sep)
    72  	var res interface{}
    73  	var success, isFinal bool
    74  	res = c.EXT
    75  	for _, k := range ks {
    76  		res, success, isFinal = find(res, k)
    77  		if !success {
    78  			return "", fmt.Errorf("no such key: %v", k)
    79  		} else if isFinal {
    80  			break
    81  		}
    82  	}
    83  	if success {
    84  		return res, nil
    85  	} else {
    86  		return "", fmt.Errorf("not found the key: %v", keys)
    87  	}
    88  }
    89  
    90  func find(v interface{}, key interface{}) (res interface{}, success, isFinal bool) {
    91  	switch m := v.(type) {
    92  	case map[string]interface{}:
    93  		res, success = m[key.(string)]
    94  		isFinal = reflect.TypeOf(res) != nil && reflect.TypeOf(res).Kind() != reflect.Map
    95  	case map[interface{}]interface{}:
    96  		res, success = m[key]
    97  		isFinal = reflect.TypeOf(res) != nil && reflect.TypeOf(res).Kind() != reflect.Map
    98  	}
    99  	return
   100  }
   101  
   102  // ExtString shortcut of Conf.ExtString
   103  func ExtString(keys string, defaultVal ...interface{}) string {
   104  	return Conf.ExtString(keys, defaultVal...)
   105  }
   106  
   107  func ExtInt(key string, defaultVal ...interface{}) int {
   108  	return Conf.ExtInt(key, defaultVal...)
   109  }
   110  func ExtFloat32(key string, defaultVal ...interface{}) float32 {
   111  	return Conf.ExtFloat32(key, defaultVal...)
   112  }
   113  func ExtFloat64(key string, defaultVal ...interface{}) float64 {
   114  	return Conf.ExtFloat64(key, defaultVal...)
   115  }
   116  func ExtBool(key string, defaultVal ...interface{}) bool {
   117  	return Conf.ExtBool(key, defaultVal...)
   118  }
   119  
   120  func ExtDuration(key string, defaultVal ...interface{}) time.Duration {
   121  	return Conf.ExtDuration(key, defaultVal...)
   122  }
   123  
   124  func (c *Config) ExtString(keys string, defaultVal ...interface{}) string {
   125  	return c.Ext(keys, defaultVal...).(string)
   126  }
   127  
   128  func (c *Config) ExtInt(key string, defaultVal ...interface{}) int {
   129  	return c.Ext(key, defaultVal...).(int)
   130  }
   131  func (c *Config) ExtFloat32(key string, defaultVal ...interface{}) float32 {
   132  	return c.Ext(key, defaultVal...).(float32)
   133  }
   134  func (c *Config) ExtFloat64(key string, defaultVal ...interface{}) float64 {
   135  	return c.Ext(key, defaultVal...).(float64)
   136  }
   137  func (c *Config) ExtBool(key string, defaultVal ...interface{}) bool {
   138  	return c.Ext(key, defaultVal...).(bool)
   139  }
   140  
   141  func (c *Config) ExtDuration(key string, defaultVal ...interface{}) time.Duration {
   142  	str := fmt.Sprintf("%v", c.Ext(key, defaultVal...))
   143  	t, _ := time.ParseDuration(str)
   144  	return t
   145  }
   146  
   147  func (d *Database) Ext(key string, defaultVal ...interface{}) interface{} {
   148  	if res, exist := d.EXT[key]; exist {
   149  		return res
   150  	}
   151  	if len(defaultVal) > 0 {
   152  		return defaultVal[0]
   153  	}
   154  	logutil.Error("the key is not exist: %v", key)
   155  	return ""
   156  }
   157  
   158  func (d *Database) ExtString(key string, defaultVal ...interface{}) string {
   159  	return d.Ext(key, defaultVal...).(string)
   160  }
   161  func (d *Database) ExtInt(key string, defaultVal ...interface{}) int {
   162  	return d.Ext(key, defaultVal...).(int)
   163  }
   164  func (d *Database) ExtFloat32(key string, defaultVal ...interface{}) float32 {
   165  	return d.Ext(key, defaultVal...).(float32)
   166  }
   167  func (d *Database) ExtFloat64(key string, defaultVal ...interface{}) float64 {
   168  	return d.Ext(key, defaultVal...).(float64)
   169  }
   170  func (d *Database) ExtBool(key string, defaultVal ...interface{}) bool {
   171  	return d.Ext(key, defaultVal...).(bool)
   172  }
   173  func (d *Database) ExtDuration(key string, defaultVal ...interface{}) time.Duration {
   174  	str := fmt.Sprintf("%v", d.Ext(key, defaultVal...))
   175  	t, _ := time.ParseDuration(str)
   176  	return t
   177  }