包toml使用反射对toml配置格式进行编码和解码。
文档: https://gowalker.org/github.com/naoina/toml
go get github.com/naoina/toml
example.toml
# This is a TOML document. Boom.
title = "TOML Example"
[owner]
name = "Lance Uppercut"
dob = 1979-05-27T07:32:00-08:00 # First class dates? Why not?
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true
[servers]
# You can indent as you please. Tabs or spaces. TOML don't care.
[servers.alpha]
ip = "10.0.0.1"
dc = "eqdc10"
[servers.beta]
ip = "10.0.0.2"
dc = "eqdc10"
[clients]
data = [ ["gamma", "delta"], [1, 2] ]
# Line breaks are OK when inside arrays
hosts = [
"alpha",
"omega"
]
package main
import (
"fmt"
"net"
"os"
"time"
"github.com/naoina/toml"
)
type Config struct {
Title string
Owner struct {
Name string
Org string `toml:"organization"`
Bio string
Dob time.Time
}
Database struct {
Server string
Ports []int
ConnectionMax uint
Enabled bool
}
Servers map[string]ServerInfo
Clients struct {
Data [][]interface{}
Hosts []string
}
}
type ServerInfo struct {
IP net.IP
DC string
}
func main() {
f, err := os.Open("./example.toml")
if err != nil {
panic(err)
}
defer f.Close()
var config Config
if err := toml.NewDecoder(f).Decode(&config); err != nil {
panic(err)
}
fmt.Println("IP of server 'alpha':", config.Servers["alpha"].IP)
// Output: IP of server 'alpha': 10.0.0.1
}
运行结果:
IP of server ‘alpha’: 10.0.0.1