いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-266 (TOMLファイルを読み込み)(toml, Unmarshal)

概要

以下、自分用のメモです。

以前にファイルI/O周りについては、以下の記事を書いていました。

devlights.hatenablog.com

TOMLファイルを読み書きする必要がありましたので、勿体ないのでここにメモメモ。。。

TOMLファイルについては、以下の情報を見ると大体わかります。Python界隈ではおなじみですね。

ja.wikipedia.org

github.com

今回は Unmarshal してみます。

GoでTOMLファイルを扱う場合は以下のライブラリが有名みたいなので、それを使っています。

github.com

ライブラリ取得

v2 が出ているので、v2側を go get します。

$ go get github.com/pelletier/go-toml/v2
go: downloading github.com/pelletier/go-toml/v2 v2.0.5
go: downloading github.com/pelletier/go-toml v1.9.5
go: added github.com/pelletier/go-toml/v2 v2.0.5

サンプル

package tomlop

import (
    "github.com/devlights/gomy/output"
    "github.com/pelletier/go-toml/v2"
)

// Unmarshal は、TOMLファイルの内容を読み込むサンプルです.
//
// # REFERENCES
//   - https://www.meetgor.com/golang-config-file-read/
//   - https://github.com/pelletier/go-toml
//   - https://ja.wikipedia.org/wiki/TOML
func Unmarshal() error {
    const (
        src = `[values]
value1 = 999
value2 = 'hello world'
value3 = false
value4 = ['one', 'two', 'three']

[author]
name = 'devlights'

[[persons]]
name = 'one'
age  = 30

[[persons]]
name = 'two'
# age は 省略

[[persons]]
name = 'three'
age  = 99`
    )

    type (
        ValuesSection struct {
            Value1 int      `toml:"value1"` // 数値
            Value2 string   `toml:"value2"` // 文字列
            Value3 bool     `toml:"value3"` // ブール
            Value4 []string `toml:"value4"` // リスト
        }

        AuthorSection struct {
            Name string // タグ指定なし
        }

        Person struct {
            Name string
            Age  int
        }

        Root struct {
            Values  ValuesSection
            Author  AuthorSection
            Persons []Person
        }
    )

    var (
        v   Root
        err error
    )

    err = toml.Unmarshal([]byte(src), &v)
    if err != nil {
        return err
    }

    output.Stdoutf("[Unmarshal]", "%+v\n", v)

    return nil
}

実行すると以下のようになります。

$ task run
task: [run] go run . -onetime

ENTER EXAMPLE NAME: toml_unmarshal

[Name] "toml_unmarshal"
[Unmarshal]          {Values:{Value1:999 Value2:hello world Value3:false Value4:[one two three]} Author:{Name:devlights} Persons:[{Name:one Age:30} {Name:two Age:0} {Name:three Age:99}]}


[Elapsed] 163.7µs

参考情報

try-golang/examples/basic/tomlop at master · devlights/try-golang · GitHub

Go言語による並行処理

Go言語による並行処理

Amazon


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。