簡體   English   中英

如何加載 toml 設置 (GOLANG)

[英]how to load toml settings (GOLANG)

我正在嘗試使用 toml 來存儲數據庫的連接設置。 我想加載 config.toml 文件中的這些設置,從而執行我的操作

我嘗試了以下:go 代碼:


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
}

配置文件:

[postgres]
host = "localhost"
port =  5432
user = "postgres"
password = "ivaneteJC"
dbname = "webhook"

此嘗試返回錯誤,不幸的是我不知道如何繼續

錯誤:

panic: interface conversion: interface {} is int64, not string

任何解決方案?

至於你的錯誤,就像@tkausl 說的那樣,你將port定義為 integer,而不是字符串,但你在這一行中將值斷言鍵入字符串

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

像錯誤所說的那樣將字符串更改為 int64,你應該沒問題。

您使用的是https://github.com/pelletier/go-toml package 嗎? 如果是這樣,這個 package 似乎也支持直接將配置文件解組為 Go 結構。 這是一種更方便的方法,而不是必須配置。 config.Get每個配置。

    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)

改動最小的方案:

// 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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM