動機
migrationツールを使うと次のようなdb.confを書いたりします。
development:
dialect: mysql
dir: db/migrations
datasource: user:password@tcp(db:3306)/db_name?charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=true
production:
dialect: postgres
dir: migrations/postgres
datasource: dbname=myapp sslmode=disable
table: migrations
せっかくなら、普通のデータベース接続もこのYAMLからデータを取ってきたい!取ってきたくない?
go-yamlを使って簡単に()実装できます!
実装例
buf, err := ioutil.ReadFile("file.pass")
if err != nil {
log.Fatal(err)
return
}
m := make(map[interface{}]interface{})
err = yaml.Unmarshal(buf, &m)
if err != nil {
log.Fatal(err)
panic(err)
}
fmt.Printf("%d\n", m["development"].(map[interface {}]interface {})["datasource"])
db_config :=m["development"].(map[interface {}]interface {})["datasource"].(string)
db, err := dbr.Open("mysql", db_config , nil)
忘備録だけど、ここに行きつくのにどちゃくそ時間がかかった……
Goのインターフェースよくわからん。ちなみにdbrを接続用のツールに使っています。
参考
https://qiita.com/umanoda/items/07887d33ef1155b26ed2
https://ota42y.com/blog/2014/11/13/go-yaml/
https://qiita.com/daiching/items/a384a5ce229cf714a3b5