//config.go: package config import ( "reflect" ) type Config struct { Values map[string]interface{} } func New(fileName string) *Config { return NewJson(fileName, nil) } func config() *Config { return &Config{Values: make(map[string]interface{})} } func (cfg *Config) toSlice(vs interface{}) []string { v := reflect.ValueOf(vs) if v.Kind() != reflect.Slice { panic("to slice error") } ret := make([]string, v.Len()) for i := 0; i < v.Len(); i++ { ret[i] = v.Index(i).Interface().(string) } return ret } func (cfg *Config) Get(keys ...string) (v interface{}) { target := cfg.Values for _, key := range keys { if v, ok := target[key]; ok { switch reflect.TypeOf(v).Kind() { case reflect.Map: target = v.(map[string]interface{}) break case reflect.Slice: return cfg.toSlice(v) default: return v } } else { return nil } } return target }
//json.go
package config import ( "encoding/json" "io/ioutil" ) func NewJson(fileName string, v interface{}) *Config { cfg := config() if v == nil { cfg.LoadJson(fileName, &cfg.Values) } else { cfg.LoadJson(fileName, &v) } return cfg } func (cfg *Config) LoadJson(fileName string, v interface{}) { data, err := ioutil.ReadFile(fileName) if err != nil { panic(err) } if err := json.Unmarshal([]byte(data), v); err != nil { panic(err) } }
//使用
cj := config.New("config.json")
sss := cj.get("XXX")