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 ?
2
Answers
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 lineChange 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.The solution with minimal changes: