先说一下,这里用到了很多关于反射类型的功能,可能刚开始看代码,如果对反射不熟悉的可能会不是非常清晰,但是同时也是为了更好的理解golang中的反射,同时如果后面想在代码中可以直接从我的git地址get:
go get github.com/pythonsite/config_yaml
直接上代码:
// 可以用于处理读yaml格式的配置文件,同时也可以用于理解golang中的反射 package config_yaml import ( "strings" "errors" "io/ioutil" "gopkg.in/yaml.v2" "reflect" "fmt" "strconv" ) type ConfigEngine struct { data map[interface{}]interface{} } // 将ymal文件中的内容进行加载 func (c *ConfigEngine) Load (path string) error { ext := c.guessFileType(path) if ext == "" { return errors.New("cant not load" + path + " config") } return c.loadFromYaml(path) } //判断配置文件名是否为yaml格式 func (c *ConfigEngine) guessFileType(path string) string { s := strings.Split(path,".") ext := s[len(s) - 1] switch ext { case "yaml","yml": return "yaml" } return "" } // 将配置yaml文件中的进行加载 func (c *ConfigEngine) loadFromYaml(path string) error { yamlS,readErr := ioutil.ReadFile(path) if readErr != nil { return readErr } // yaml解析的时候c.data如果没有被初始化,会自动为你做初始化 err := yaml.Unmarshal(yamlS, &c.data) if err != nil { return errors.New("can not parse "+ path + " config" ) } return nil } // 从配置文件中获取值 func (c *ConfigEngine) Get(name string) interface{}{ path := strings.Split(name,".") data := c.data for key, value := range path { v, ok := data[value] if !ok { break } if (key + 1) == len(path) { return v } if reflect.TypeOf(v).String() == "map[interface {}]interface {}"{ data = v.(map[interface {}]interface {}) } } return nil } // 从配置文件中获取string类型的值 func (c *ConfigEngine) GetString(name string) string { value := c.Get(name) switch value:=value.(type){ case string: return value case bool,float64,int: return fmt.Sprint(value) default: return "" } } // 从配置文件中获取int类型的值 func (c *ConfigEngine) GetInt(name string) int { value := c.Get(name) switch value := value.(type){ case string: i,_:= strconv.Atoi(value) return i case int: return value case bool: if value{ return 1 } return 0 case float64: return int(value) default: return 0 } } // 从配置文件中获取bool类型的值 func (c *ConfigEngine) GetBool(name string) bool { value := c.Get(name) switch value := value.(type){ case string: str,_:= strconv.ParseBool(value) return str case int: if value != 0 { return true } return false case bool: return value case float64: if value != 0.0 { return true } return false default: return false } } // 从配置文件中获取Float64类型的值 func (c *ConfigEngine) GetFloat64(name string) float64 { value := c.Get(name) switch value := value.(type){ case string: str,_ := strconv.ParseFloat(value,64) return str case int: return float64(value) case bool: if value { return float64(1) } return float64(0) case float64: return value default: return float64(0) } } // 从配置文件中获取Struct类型的值,这里的struct是你自己定义的根据配置文件 func (c *ConfigEngine) GetStruct(name string,s interface{}) interface{}{ d := c.Get(name) switch d.(type){ case string: c.setField(s,name,d) case map[interface{}]interface{}: c.mapToStruct(d.(map[interface