您的位置 首页 golang

Golang toml类型配置文件应用

TOML 的全称是 Tom’s Obvious, Minimal Language,作者是 GitHub 联合创始人 Tom Preston-Werner。

TOML 的目标是成为一个极简的配置文件格式。TOML 被设计成可以无歧义地被映射为 哈希表 ,从而被多种语言解析。

类似mysql, redis 的配置文件都是使用toml格式,现在也越来越受Go开发者的喜爱,通俗易懂的风格,多数据结构支持,操作简单。

conf.toml文件格式

[client]

port = 3306

[mysqld]

user = “mysql”

open_files_limit = 10240

示例:

package main

import (

“sync”

“path/filepath”

“fmt”

“github.com/BurntSushi/toml”

)

type tomlConfig struct {

Client client

Mysqld mysqld

}

type client struct {

Port int

}

type mysqld struct {

User string

Limit int `toml:”open_files_limit”`

}

var (

cfg * tomlConfig

once sync.Once

)

func Config() *toml Config {

once.Do(func() {

filePath, err := filepath.Abs(“./linshi/conf.toml”)

if err != nil {

panic(err)

}

fmt.Printf(“parse toml file once. filePath: %s\n”, filePath)

if _ , err := toml.DecodeFile(filePath, &cfg); err != nil {

panic(err)

}

})

return cfg

}

func main() {

fmt.Println(Config().Mysqld.User)

}

执行结果:

parse toml file once. filePath: C:\Go\Workspace\linshi\conf.toml

mysql

注意:

1 结构体 的成员首字母大写

2 配置文件的配置项须与结构体成员名一样

3 支持 bool ,int,float, 字符串 ,字符串数组等

4.加载配置项sync.Once使用

更多内容请关注每日编程,每天进步一点。

文章来源:智云一二三科技

文章标题:Golang toml类型配置文件应用

文章地址:https://www.zhihuclub.com/88326.shtml

关于作者: 智云科技

热门文章

网站地图