go语言学习之----读取配置文件的方式toml
来源:互联网 发布:js表单验证表示时间 编辑:程序博客网 时间:2024/06/08 04:47
最近go语言项目中用到读取配置文件,如下:
使用这个"github.com/BurntSushi/toml"
配置文件如下:conf.toml
# idID = 1# nameName = "name1"# weightWeight = 1.7# booksBooks = ["a", "b", "c"]Sex = true#friend Friend都可以[friend]Age = 32Name = "xio"
代码如下 readConf.go:
package confimport ("fmt""github.com/BurntSushi/toml""io/ioutil""os")// persontype Person struct {ID uint32Sex boolName stringWeight float32Friend *FriendsBooks []string}// friendstype Friends struct {Age intName string}func ReadConf(fname string) (p *Person, err error) {var (fp *os.Filefcontent []byte)p = new(Person) // &Person{}if fp, err = os.Open(fname); err != nil {fmt.Println("open error ", err)return}if fcontent, err = ioutil.ReadAll(fp); err != nil {fmt.Println("ReadAll error ", err)return}if err = toml.Unmarshal(fcontent, p); err != nil {fmt.Println("toml.Unmarshal error ", err)return}return}
测试代码如下 readConf_test.go:
package confimport "testing"func TestReadConf(t *testing.T) {p, err := ReadConf("./conf.toml")if err != nil {t.Logf("%v", err)}t.Logf("person %v", p)t.Logf("person.friend %v", p.Friend)}
输出结果为:
[ `go test -v` | done: 2.6748515s ] === RUN TestReadConf --- PASS: TestReadConf (0.00s) readConf_test.go:11: person &{1 true name1 1.7 0x1218c570 [a b c]} readConf_test.go:12: person.friend &{32 xio} PASS ok goProgram/conf 0.458s
细节点:
1 结构体的成员首字母大写
2 配置文件的配置项须与结构体成员名一样
3 支持bool, int, float , 字符串,字符串数组...等,
也可以包含其他结构体 如[Friend]
附:学习链接
https://item.congci.com/-/content/toml-ji-jian-de-peizhiwenjian-geshi
https://github.com/toml-lang/toml
0 0
- go语言学习之----读取配置文件的方式toml
- go语言配置文件解析库的使用TOML parser and encoder for Go with reflection
- Go实战--也许最快的Go语言Web框架kataras/iris初识二(TOML、Cache、Cookie)
- 读取配置文件[方式一]之纯C语言实现
- Go语言学习7:Go语言为什么要用变量名后置的方式做声明
- go语言学习-接口赋值的两种方式
- Go语言的学习
- java 学习笔记 读取配置文件的三种方式
- 关于配置文件的读取方式.
- Java读取配置文件的方式
- java读取配置文件的方式
- java读取配置文件的方式
- Spring读取配置文件的方式
- Go语言学习之数据类型
- GO语言学习之goroutine
- go语言中yaml配置文件的使用
- toml
- 传智播客学习之读取配置文件
- CentOS下Mysql的安装与配置
- JSPath使用汇总
- sublime text 配置本地静态服务器方法
- 关于图像目标检测的HOG\LBP\Harr特征的博客
- vmware12中安装winxp
- go语言学习之----读取配置文件的方式toml
- 20170214C语言提升08_指针_01变量及指针及数组
- 欢迎使用CSDN-markdown编辑器
- IPC-Messenger使用实例
- Java实现几种常见排序方法
- Spring security下csrf token的认证
- 淘宝技术这十年
- Spring cloud Eureka服务注册及发现(二)创建注册服务
- 新建服务器的相关开发配置-----jdk配置