Unable to decode toml file

Issue

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

Solution

你的“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, 最好做一下非空判断并log一下

Answered By – Comin2021

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.