LoginSignup
17
11

More than 5 years have passed since last update.

viperでファイルを読み込んで構造体にマッピングする

Posted at

はじめに

viperを使ってconfファイルを読もうとして、無駄に2時間程度はまってしまった。
同じような人もいると思うので、この記事に簡単に残しておく。

ソースコード

やりたい事は、config.ymlを読み込ませて、構造体にマッピングする。

//conf.go
type config struct {
    /*
        yml形式に合わせて構造体で記述する。
        先頭の文字が大文字でないとUnmarshalで読み込めない
        https://qiita.com/hachi8833/items/fe3d5d6b1285c5ef1821
        バグであるのかも
    */
    Database struct {
        Host     string
        Port     string
        User     string
        Password string
    }
}

func Configure() {
    // 外部からconfの中身を参照できるようにする
    var C config

    // 設定ファイル名を記載
    viper.SetConfigName("config")

    // ファイルタイプ
    viper.SetConfigType("yml")

    // ファイルパスの設定。クロスプラットフォームで参照できるようにfilepathライブラリを使用
    viper.AddConfigPath(filepath.Join("$GOPATH", "src", "github.com", "yoshinorihisakawa", "sample-api-hoop", "conf"))

    // 環境変数から設定値を上書きできるように設定
    viper.AutomaticEnv()

    // conf読み取り
    if err := viper.ReadInConfig(); err != nil {
        fmt.Println("config file read error")
        fmt.Println(err)
        os.Exit(1)
    }

    // UnmarshalしてCにマッピング
    if err := viper.Unmarshal(&C); err != nil {
        fmt.Println("config file Unmarshal error")
        fmt.Println(err)
        os.Exit(1)
    }
}
// config.yml
database:
    host: "127.0.0.1"
    port: "3306"
    user: "postgres"
    password: "yoshi0923"

ハマったポイント

・SetConfigNameでなくSetConfigFileとしてしまっていた。
 SetConfigFileを使う場合は、ファイルのパス全て参照させる必要がある。
 ライブラリの中を追いまくっておかしいと思い、docを見て気づいた。

・構造体の先頭文字を大文字にしなければUnmarshalしてくれない。
 ソースおってもよくわからなかった。
 ただこれは注意事項として覚えておいた方がよさそう。ネットでググって解決した。

17
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
11