英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论