2
2

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.

Goでtoml.DecodeFileしたときにハマったことメモ

Posted at
182b65b9 539c 4d24 9b1f ee4a1a8756f1 TOMLという設定ファイルの為のミニ言語があり、それをGoで試してみた所、うまく読み込まれずにハマってしまったので、メモ。

config_test.go


package main

import (
	"github.com/BurntSushi/toml"
	"testing"
	"fmt"
)

type ConfToml struct {
	Keys SectionKeys `toml:"keys"`
}

type SectionKeys struct {
	Consumer_key string `toml:"consumer_key"`
	access_token string `toml:"access_token"`
}

// config の read
func readSettingsConfig(path string, config *ConfToml) {
	_, err := toml.DecodeFile(path, config)
	if err != nil {
		panic(err)
	}
}

func Test_readSettingsConfg(t *testing.T) {
	var conftoml ConfToml

	_, err := toml.DecodeFile("config.toml", &conftoml)	
	if err != nil {
		panic(err)
	}
	
 	fmt.Println(conftoml.Keys)

	// Printlnする為に、あえてerrorにしている。
 	if conftoml.Keys.Consumer_key != "aab" {
 		t.Error("Not Match")
 	}
 	if conftoml.Keys.Consumer_key != "bbb" {
 		t.Error("Not Match")
 	}

}

config.toml


[keys]
consumer_key = "aaa"
access_token = "bbb"

実行結果


{aaa }
--- FAIL: Test_readSettingsConfg (0.00s)
        config_test.go:38: Not Match
        config_test.go:41: Not Match
FAIL
FAIL    command-line-arguments  0.005s

この太字にしたところがポイントで、これはtomlファイルを読み込んだ構造体をPrintlnしているのですが、aaaという値だけ格納されている状態です。
本来ならば、{aaa bbb}となるはずです。


type SectionKeys struct {
	Consumer_key string `toml:"consumer_key"`
	access_token string `toml:"access_token"`
}

このSectionKesyという構造体のフィールド名が小文字と大文字で違っているのが原因です。
どうやらDecodeFileはフィールド名が小文字だと値が設定されないようです。
※Access_tokenと大文字で設定すると正しく値は設定されました。

恐らくですが、github.com/BurntSushi/tomlパッケージ外の構造体へのアクセス権限がない(エクスポートできない)のが原因かと思っています。
値が設定されず、やだな〜やだな〜こわいなーこわいな〜とハマっておりました。

謝った認識かもしれませんので、ご指導ご鞭撻のほどよろしくお願いします。

参考サイト

【個人メモ】設定ファイルフォーマットにはTOMLがいいのかも Go言語での構造体実装パターン
2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?