1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

yamlから欲しい情報をGoでとる(マイグレーションツールを使うときに使うファイルを流用する)

Posted at

動機

 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

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?