-
获取包
go get github.com/BurntSushi/toml
-
添加.toml文件
[env]
debug = true
host = "127.0.0.1"
port = 1080
ips = ["127.0.0.1", "127.0.0.2", "127.0.0.3"]
ids = [1, 2, 3]
[dbs.master]
host = "127.0.0.1"
port = 3306
[dbs.slave]
host = "127.0.0.1"
port = 3306
[[fruit]]
name = "apple"
[fruit.physical]
color = "red"
shape = "round"
[[fruit.variety]]
name = "red delicious"
[[fruite.variety]]
[[fruit.variety]]
name = "granny smith"
[[fruit]]
name = "banana"
[[fruit.variety]]
name = "plantain"
-
根据toml文件创建对应go结构
package config
import (
"fmt"
"github.com/BurntSushi/toml"
)
var config *Config
type Config struct {
EnvConfig *EnvConfig `toml:"env"`
DBConfigs map[string]*DBConfig `toml:"dbs"`
Fruits []*Fruit `toml:"fruit"`
}
func (c *Config) String() string {
return fmt.Sprintf("%+v", *c)
}
type EnvConfig struct {
Debug bool `toml:"debug"`
Host string `toml:"host"`
Port int `toml:"port"`
IPs []string `toml:"ips"`
Ids []int `toml:"ids"`
}
func (c *EnvConfig) String() string {
return fmt.Sprintf("%+v", *c)
}
type DBConfig struct {
Host string `toml:"host"`
Port int `toml:"port"`
}
func (c *DBConfig) String() string {
return fmt.Sprintf("%+v", *c)
}
type Fruit struct {
Name string `toml:"name"`
Physical *Physical `toml:"physical"`
Varieties []*Variety `toml:"variety"`
}
func (c *Fruit) String() string {
return fmt.Sprintf("%+v", *c)
}
type Physical struct {
Color string `toml:"color"`
Shape string `toml:"shape"`
}
func (c *Physical) String() string {
return fmt.Sprintf("%+v", *c)
}
type Variety struct {
Name string `toml:"name"`
}
func (c *Variety) String() string {
return fmt.Sprintf("%+v", *c)
}
func Init(file string) error {
config = &Config{}
_, err := toml.DecodeFile(file, config)
if err != nil {
return err
}
return nil
}
func GetConfig() *Config {
return config
}
-
调用
package main
import (
"fmt"
"gosports/gateway/config"
)
func main() {
err := config.Init("gateway.toml")
if err != nil{
fmt.Printf("Init config failed! err: %s", err)
}
conf := config.GetConfig()
fmt.Printf("config: %+v", conf)
}
-
结果
config: {EnvConfig:{Debug:true Host:127.0.0.1 Port:1080 IPs:[127.0.0.1 127.0.0.2 127.0.0.3] Ids:[1 2 3]} DBConfigs:map[master:{Host:127.0.0.1 Port:3306} slave:{Host:127.0.0.1 Port:3306}] Fruits:[{Name:apple Physical:{Color:red Shape:round} Varieties:[{Name:red delicious} {Name:granny smith}]} {Name:banana Physical:<nil> Varieties:[{Name:plantain}]}]}
-
toml教程参考