;INI文件由节、键、值组成。
[mysql]
host = 192.168.xxx.xxx
port = 3306
charset = "utf8"
直接读取:
//go get github.com/Unknwon/goconfig
func main() {
cfg, err := goconfig.LoadConfigFile("conf.ini")
if err != nil {
panic("错误")
}
//单值
host, _ := cfg.GetValue("mysql", "host")
port, _ := cfg.Int("mysql", "port")
fmt.Println(host, port, show)
//节点
cfgMap, err := cfg.GetSection("mysql")
fmt.Println(cfgMap["host"])
}
反序列化:
type IniConf struct {
Mysql struct {
Host string
Port int
Charset string
}
}
//go get gopkg.in/gcfg.v1
func main() {
conf :=new(IniConf)
err := gcfg.ReadFileInto(conf, "conf.ini")
if err != nil {
panic(err)
}
fmt.Println(conf.Mysql.Host, conf.Mysql.Port)
}
host: 192.168.0.1
port: 3306
user: root
pwd: 123456
db: testdb
charset: "utf8"
直接读取:
// go get -u github.com/kylelemons/go-gypsy
func main() {
conf, err := yaml.ReadFile("conf.yaml")
if err != nil {
fmt.Println(err)
}
fmt.Println(conf.Get("host"))
fmt.Println(conf.GetInt("port"))
}
反序列化:
https://github.com/go-yaml/yaml
// go get gopkg.in/yaml.v2
func main() {
c := NewYamlConf("conf.yaml")
fmt.Printf("%s:%s@tcp(%s:%d)/%s?charset=%s\n", c.User, c.Pwd, c.Host, c.Port, c.Db, c.Charset)
}
type YamlConf struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
User string `yaml:"user"`
Pwd string `yaml:"pwd"`
Db string `yaml:"db"`
Charset string `yaml:"charset"`
}
func NewYamlConf(path string) *YamlConf {
ym := new(YamlConf)
yf, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
err = yaml.Unmarshal(yf, ym)
if err != nil {
panic(err)
}
return ym
}
{
"host": "192.168.0.1",
"port": 3306,
"charset": "utf8"
}
//Json配置对象
type JsonConf struct {
Host string
Port int
Charset string
}
func main() {
jf, err := os.Open("conf.json")
if err != nil {
panic(err)
}
defer jf.Close()
conf := JsonConf{}
if err := json.NewDecoder(jf).Decode(&conf); err != nil {
panic(err)
}
fmt.Println(conf.Host, conf.Port)
}