如何加载 TOML 设置(GOLANG)

huangapple go评论86阅读模式
英文:

how to load toml settings (GOLANG)

问题

我正在尝试使用TOML来存储数据库的连接设置。
我想要加载一个名为config.toml的文件中的这些设置,然后执行我的操作。

我尝试了以下代码:
Go代码:

func Init() *sql.DB {
    config, err := toml.LoadFile("config.toml")
    if err != nil {
        log.Fatal("Erro ao carregar variaveis de ambiente")
    }

    host := config.Get("postgres.host").(string)
    port := config.Get("postgres.port").(int64)
    user := config.Get("postgres.user").(string)
    password := config.Get("postgres.password").(string)
    dbname := config.Get("postgres.dbname").(string)

    stringConnection := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s", host, port, user, password, dbname)

    db, err := sql.Open("postgres", stringConnection)

    if err != nil {
        panic(err)
    }
    fmt.Println("Sucesso ao realizar conexão com o banco de dados")

    err = db.Ping()
    return db
}

config.toml:

[postgres]
host = "localhost"
port = 5432
user = "postgres"
password = "ivaneteJC"
dbname = "webhook"

这个尝试返回了一个错误,不幸的是我不知道如何继续处理。

错误信息:

panic: interface conversion: interface {} is int64, not string

有什么解决办法吗?

英文:

I'm trying to use toml to store the connection settings of a database.
I want to load these settings that are in a config.toml file and thus do my operations

I tried the following:
go code:


func Init() *sql.DB {

	config, err := toml.LoadFile("config.toml")
	if err != nil {
		log.Fatal("Erro ao carregar variaveis de ambiente")
	}

	host := config.Get("postgres.host").(string)
	port := config.Get("postgres.port").(string)
	user := config.Get("postgres.user").(string)
	password := config.Get("postgres.password").(string)
	dbname := config.Get("postgres.dbname").(string)

	stringConnection := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s", host, port, user, password, dbname)

	db, err := sql.Open("postgres", stringConnection)

	if err != nil {
		panic(err)
	}
	fmt.Println("Sucesso ao realizar conexão com o banco de dados")

	err = db.Ping()
	return db
}

config.toml:

[postgres]
host = "localhost"
port =  5432
user = "postgres"
password = "ivaneteJC"
dbname = "webhook"

this attempt is returning an error, which unfortunately I do not know how to proceed

error:

panic: interface conversion: interface {} is int64, not string

Any solution ?

答案1

得分: 2

关于你的错误,就像 @tkausl 所说,你将 port 定义为整数,而不是字符串,然而你在这一行中对值进行了字符串类型断言:

port := config.Get("postgres.port").(string)

按照错误提示所说,将字符串改为 int64 类型,问题就会解决。

你是否在使用 https://github.com/pelletier/go-toml 包?如果是的话,这个包似乎还支持将配置文件直接解组为 Go 结构体。这是一种更方便的方法,而不是逐个使用 config.Get 获取每个配置。

type PostgreConfig struct {
    Host     string
    Port     int
    User     string
    Password string
    Dbname   string
}

type MyConfig struct {
    Postgres *PostgreConfig
}

// 读取 toml 文件内容
doc, err := os.ReadFile("config.toml")
if err != nil {
    panic(err)
}

// 解析内容
var cfg MyConfig
err = toml.Unmarshal(doc, &cfg)
if err != nil {
    panic(err)
}

fmt.Println(cfg.Postgres.Host)
fmt.Println(cfg.Postgres.Port)
英文:

As for your error, like @tkausl said, you define port as integer, and not a string, yet you do type assertion of the value to string in this line

port := config.Get("postgres.port").(string)

Change the string to int64 like the error said and you should be fine.

Are you using the https://github.com/pelletier/go-toml package? If so, this package seems to also support unmarshalling config files into Go struct directly. This is a more convenient approach instead of having to config.Get each config one by one.

    type PostgreConfig struct {
		Host     string
		Port     int
		User     string
		Password string
		Dbname   string
	}

	type MyConfig struct {
		Postgres *PostgreConfig
	}

	// Read the toml file content
	doc, err := os.ReadFile("config.toml")
	if err != nil {
		panic(err)
	}

	// Parse the content
	var cfg MyConfig
	err = toml.Unmarshal(doc, &cfg)
	if err != nil {
		panic(err)
	}

	fmt.Println(cfg.Postgres.Host)
	fmt.Println(cfg.Postgres.Port)

答案2

得分: 1

最小更改的解决方案:

// 解决方案1
port := config.Get("postgres.port")
stringConnection := fmt.Sprintf("host=%s port=%v user=%s password=%s dbname=%s", host, port, user, password, dbname)

// 解决方案2
port := config.Get("postgres.port").(int64)
stringConnection := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s", host, port, user, password, dbname)

// 解决方案3
// config.toml
port = "5432"
英文:

The solution with minimal changes:

// solution 1
port := config.Get("postgres.port")
stringConnection := fmt.Sprintf("host=%s port=%v user=%s password=%s dbname=%s", host, port, user, password, dbname)

// solution 2
port := config.Get("postgres.port").(int64)
stringConnection := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s", host, port, user, password, dbname)

// solution 3
// config.toml
port =  "5432"

huangapple
  • 本文由 发表于 2022年12月28日 04:08:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/74933714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定