无法解码 TOML 文件

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

Unable to decode toml file

问题

我想从一个toml文件中读取配置。

conf/conf.toml

db_host = "127.0.0.1"

db_port = 3306

db_user = "root"

db_password ="123456"

conf/conf.go文件

package conf

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

type appcfg struct {
	DbHost     string `toml:"db_host"`
	DbPort     string `toml:"db_port"`
	DbUser     string `toml:"db_user"`
	DbPassword string `toml:"db_password"`
}

var (
	App       *appcfg
	defConfig = "./conf/conf.toml"
)

func init() {

	var err error
	App, err = initCfg()
    log.Println(App.DbHost)

}

func initCfg() (*appcfg, error) {
	app := &appcfg{}
	_, err := toml.DecodeFile(defConfig, &app)
	if err != nil {
		return nil, err
	}
	return app, nil
}

当我运行这个程序时,我得到一个我不知道如何修复的错误:

panic: runtime error: invalid memory address or nil pointer dereference

英文:

I want to read configs from a toml file.

conf/conf.toml

db_host = "127.0.0.1"

db_port = 3306

db_user = "root"

db_password ="123456"

conf/conf.go file

package conf

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

type appcfg struct {
	DbHost     string `toml:"db_host"`
	DbPort     string `toml:"db_port"`
	DbUser     string `toml:"db_user"`
	DbPassword string `toml:"db_password"`
}

var (
	App       *appcfg
	defConfig = "./conf/conf.toml"
)

func init() {

	var err error
	App, err = initCfg()
    log.Println(App.DbHost)

}

func initCfg() (*appcfg, error) {
	app := &appcfg{}
	_, err := toml.DecodeFile(defConfig, &app)
	if err != nil {
		return nil, err
	}
	return app, nil
}

When I run this program, I get an error that I don't know how to fix:

> panic: runtime error: invalid memory address or nil pointer dereference

答案1

得分: 0

(重新发布Comin2021的现已删除的答案,因为它被提问者接受了)

你将DbPort的类型定义为string,但在你的配置文件中它显示为整数。请按以下方式进行更改:

type appcfg struct {
    DbHost     string `toml:"db_host"`
    DbPort     int64  `toml:"db_port"`  // 将此处更改
    DbUser     string `toml:"db_user"`
    DbPassword string `toml:"db_password"`
}

还要检查initCfg的第二个返回值err是否为空,并将其记录下来。

英文:

(Reposting Comin2021's now deleted answer in English, since it was accepted by the OP)

You defined the type of your DbPort as string but it appears as an integer in your configuration file. Change it as below:

type appcfg struct {
    DbHost     string `toml:"db_host"`
    DbPort     int64  `toml:"db_port"`  // change this
    DbUser     string `toml:"db_user"`
    DbPassword string `toml:"db_password"`
}

Also check that initCfg second return value err is not empty and log it.

huangapple
  • 本文由 发表于 2022年5月24日 14:17:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/72358006.html
匿名

发表评论

匿名网友

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

确定