Go言語で開発用、本番用などで環境ごとに設定ファイルを切り替える方法。
設定ファイルはTOML言語で記述する。
事前準備
github.com/BurntSushi/tomlを取得しておく。
go get github.com/BurntSushi/toml
実装
開発用設定ファイル
development.toml
url = "http://localhost:3000/"
本番用設定ファイル
production.toml
url = "http://192.168.0.1:3000/"
設定ファイル管理プログラム
package config
import (
"sync"
"github.com/BurntSushi/toml"
)
type Config struct {
// ここにTOMLと紐づけされる設定値を定義する。
URL string `toml:"url"`
}
var instance *Config
var once sync.Once
func Get() *Config {
return instance
}
func Init(e string) {
once.Do(func() {
env := e
if e == "" {
env = "development"
}
instance = &Config{}
toml.DecodeFile("config/"+env+".toml", instance)
})
}
アプリの初期処理で上記のInit関数を実行する。
import (
"app/config"
)
func initEnv() {
// アプリの起動引数にdevelopmentやproductionという文字列が指定される想定。
if len(os.Args) > 1 {
config.Init(os.Args[1])
} else {
config.Init("")
}
}
設定値の使用方法
import (
"app/config"
)
func main() {
url := config.Get().URL
}