$ go get gopkg.in/yaml.v2
package config import ( "io/ioutil" "path/filepath" "fmt" "gopkg.in/yaml.v2" ) type config struct { Database databaseConfig `yaml:"database"` } type databaseConfig struct { Username string Password string } var Db databaseConfig func init() { filePath := "/path/to/config.yml" file, err := ioutil.ReadFile(filePath) if err != nil { fmt.Println(err) } var conf config err = yaml.Unmarshal([]byte(file), &conf) if err != nil { fmt.Println(err) } Db = conf.Database }
追記
configパッケージを使い回せるように変更(sync.Onceを利用)
“`
package config import ( "io/ioutil" "path/filepath" "fmt" "sync" "gopkg.in/yaml.v2" ) type config struct { Database databaseConfig `yaml:"database"` } type databaseConfig struct { Username string Password string } var once = new(sync.Once) var Db databaseConfig func init() { once.Do(func(){ filePath := "/path/to/config.yml" file, err := ioutil.ReadFile(filePath) if err != nil { fmt.Println(err) } var conf config err = yaml.Unmarshal([]byte(file), &conf) if err != nil { fmt.Println(err) } Db = conf.Database }) }