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
CodePudding user response:
(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.