golang naoina/toml

该博客介绍了如何在Golang中使用naoina/toml库进行 TOML 配置文件的编码和解码操作,通过反射机制实现配置解析,并提供了一个简单的示例和相关文档链接。
摘要由CSDN通过智能技术生成

包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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值