Home > Net >  how to load toml settings (GOLANG)
how to load toml settings (GOLANG)

Time:12-28

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 ?

CodePudding user response:

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 line

port := config.Get("postgres.port").(string)

Change 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.

    type PostgreConfig struct {
        Host     string
        Port     int
        User     string
        Password string
        Dbname   string
    }

    type MyConfig struct {
        Postgres *PostgreConfig
    }

    // Read the toml file content
    doc, err := os.ReadFile("config.toml")
    if err != nil {
        panic(err)
    }

    // Parse the content
    var cfg MyConfig
    err = toml.Unmarshal(doc, &cfg)
    if err != nil {
        panic(err)
    }

    fmt.Println(cfg.Postgres.Host)
    fmt.Println(cfg.Postgres.Port)

CodePudding user response:

The solution with minimal changes:

// solution 1
port := config.Get("postgres.port")
stringConnection := fmt.Sprintf("host=%s port=%v user=%s password=%s dbname=%s", host, port, user, password, dbname)

// solution 2
port := config.Get("postgres.port").(int64)
stringConnection := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s", host, port, user, password, dbname)

// solution 3
// config.toml
port =  "5432"
  • Related