Go 每日一库之 go-ini

darjun ·
jan-bar
想要拥有,必定付出。
我自己写的自己用的读取ini文件,虽然很简单但够我用了。分享一波。 ```go package config import ( "bufio" "bytes" "io" "os" "strconv" ) type ( Value string Option map[string]Value IniConfig map[string]Option ) func LoadConfig(path string) (IniConfig, error) { fr, err := os.Open(path) if err != nil { return nil, err } defer fr.Close() var ( index = 0 section = "" r = bufio.NewReader(fr) cnf = make(IniConfig, 8) ) for { line, _, err := r.ReadLine() if err != nil { if err == io.EOF { return cnf, nil } return nil, err } if line = bytes.TrimSpace(line); len(line) == 0 { continue } s := bytes.IndexAny(line, ";#") if s == 0 { continue } else if s > 0 { line = line[:s] } if s = bytes.IndexByte(line, '['); s >= 0 { if e := bytes.IndexByte(line[s:], ']'); e > s { section = string(line[s+1 : e]) cnf[section] = make(Option, 8) cnf[section]["index"] = Value(strconv.Itoa(index)) index++ } } else if s = bytes.IndexByte(line, '='); s > 0 && section != "" { cnf[section][string(bytes.TrimSpace(line[:s]))] = Value(bytes.TrimSpace(line[s+1:])) } } } func (c IniConfig) GetOption(section string) Option { if ks, ok := c[section]; ok { return ks } return nil } func (o Option) GetValue(option string) Value { if ko, ok := o[option]; ok { return ko } return "" } func (c IniConfig) GetValue(section, option string) Value { if ks, ok := c[section]; ok { if ko, ok := ks[option]; ok { return ko } } return "" } func (v Value) ToString(defValue string) string { if v == "" { return defValue } return string(v) } func (v Value) ToBool(defValue bool) bool { if b, err := strconv.ParseBool(string(v)); err == nil { return b } return defValue } func (v Value) ToInt(defValue int) int { if i, err := strconv.Atoi(string(v)); err == nil { return i } return defValue } func toInt64(s Value, factor, defValue int64) int64 { if i, err := strconv.ParseInt(string(s), 10, 0); err == nil { return i * factor } return defValue } func (v Value) ToBytes(defValue int64) int64 { if len(v) > 2 { switch str := v[:len(v)-2]; v[len(v)-2:] { case "KB": return toInt64(str, 1024, defValue) case "MB": return toInt64(str, 1024*1024, defValue) case "GB": return toInt64(str, 1024*1024*1024, defValue) } } return toInt64(v, 1, defValue) } ```
#1