首页 > 其他分享 >go之toml包实战

go之toml包实战

时间:2023-01-16 18:15:01浏览次数:40  
标签:实战 Log err setting toml Mysql go string

go的toml包使用案例

  • toml包【github.com/BurntSushi/toml】作用是将配置文件解析到结构体中,本文带你如何实现

1、toml文件

# 是key=value书写类型
[Mysql]
UserName = "testdb"
Password = "123456"
IpHost = "127.0.0.1:3306"
DbName = "test_db"

[Log]
LogFilePath = "log"
LogTime = 7

2、对应的结构体

type Config struct {
	Mysql *Mysql
	Log   *Log
}

type Mysql struct {
	UserName string
	Password string
	IpHost   string
	DbName   string
}

type Log struct {
	LogFilePath string
	LogTime     int
}

3、使用toml包解析配置文件到结构体中

package setting

import (
	"github.com/BurntSushi/toml"
)

var (
    // 变量应是导出的
	Conf = &Config{}
)

func Init() error {
    // 配置文件路径路径、解析的结构体
	if _, err := toml.DecodeFile("conf/conf.toml", &Conf); err != nil {
		return err
	}
	return nil
}

4、在main中调用

package main

import (
	"fmt"
	"tomlx/setting"
)

func main() {
	err := setting.Init()
	if err != nil {
		fmt.Printf("加载配置文件失败: %s\n", err)
	}
	
	fmt.Println(setting.Conf.Log)
	fmt.Println(setting.Conf.Mysql)
}

标签:实战,Log,err,setting,toml,Mysql,go,string
From: https://www.cnblogs.com/hsyw/p/17056044.html

相关文章