envconfig

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2022 License: Apache-2.0 Imports: 8 Imported by: 1

README

go-envconfig

設定ファイルと環境変数から値を取得してstructにセットします。

特徴

  • 設定なしでもつかえる
  • 設定ファイルの位置、名前は自由
  • 設定をsliceに格納することができる
  • structが階層化されていても大丈夫

インストール

go get https://github.com/yakumo-saki/go-envconfig

Getting started

(オプション)設定ファイルを作成する

STR_CONF=value_from_config_file
INT_CONF=1234

(オプション)環境変数をセットする

STR_CONF=value_from_env
package main

type Conf struct {
    StrConf string
    IntConf int
}

func main() {
    envconfig.AddPath("path/to/your/config")
    envconfig.AddPath("path/to/your/another/config")
    
    cfg := Conf{}
    err := envconfig.LoadConfig(&cfg)
    if err != nil {
        panic(err)
    }

    fmt.Println(cfg.StrConf) // "value_from_config_file" or "value_from_env"
    fmt.Println(cfg.IntConf) // 1234
}

基本動作

  • envconfig.AddPath() で追加された順番に設定ファイルを読み込みます。
  • なお、指定された設定ファイルが存在しない場合は無視します
  • envconfig.AddPath()されたファイルを読み終わった後に環境変数を読み込みます。
  • 同一の設定が存在する場合、後に出現したものが優先されます。

Advanced

デフォルト値を入れたい

envconfig.LoadConfigに渡すstructに値をセットしてから渡すことで設定可能。

func main() {
    cfg := Conf{}
    cfg.StrConf = "default value"

    err := envconfig.LoadConfig(&cfg)
    fmt.Println(cfg.StrConf) // "default value"
}
設定のキーを指定したい

デフォルトでは、フィールド名をUPPER_SNAKE_CASEにしたものが設定のキーとして使用されます。
以下の例であれば、STR_CONF が使用されます。これを変更したい場合は以下のように指定します。

type Conf struct {
    StrConf string `cfg:"MY_CONFIG"`
}
連番で入力した設定をSliceで欲しい

cfgタグの二番目のオプションに slice を追加することで可能です。

type Conf struct {
    SliceConfig []string `cfg:"SLICE_CONFIG,slice"`
}

SLICE_CONFIG0,SLICE_CONFIG00, SLICE_CONFIG1,SLICE_CONFIG01, ...SLICE_CONFIG99 までを探してSliceにして読み込む。連番でなくてもOK。 この設定の場合は、複数のファイルに SLICE_CONFIGnnが一つでもある場合上書きされる。

note: 上記の例の場合、SLICE_CONFIG というキーは読み込まれないことに注意

sliceの例
SLICE_CONFIG00=abc
SLICE_CONFIG00=xyz

→ SLICE_CONFIG = []string{"xyz"}
"abc" は上書きされる。

複数ファイルにあるsliceを上書きではなくマージしたい

cfgタグの二番目のオプションに mergeslice を追加することで可能です。

type Conf struct {
    SliceConfig []string `cfg:"SLICE_CONFIG,mergeslice"`
}
実行例
SLICE_CONFIG00=abc
SLICE_CONFIG00=xyz

→ SLICE_CONFIG = []string{"abc", "xyz"}

指定したフィールド以外に値をセットしない
TEST=this is not read
type SimpleConfig struct {
	Test string
}

func main() {
    cfg := SimpleConfig{}
    
    // Use Strict mode.
    UseStrict() 
    
    envconfig.LoadConfig(&cfg)
    fmt.Println(cfg.Test)  // empty. not "this is not read"
}

制限

一度定義されたsliceを空にすることはできません
SLICE_0=abc
SLICE_1=def
# これで上書きしても、[]string = {""} となり空にはなりません。
SLICE_0=

Documentation

Index

Constants

View Source
const TAG = "cfg"

Variables

This section is empty.

Functions

func AddPath

func AddPath(path string) int

AddPath adds config read path.

every path not needs to be existed. If file not found on path, its simply ignored.

Same config are overwrite by last added config file. returns path count added

func ClearPath

func ClearPath()

func EnableLog

func EnableLog(debug, warn func(format string, a ...interface{}))

EnableLog enables logging with specified log output function. Not output log if function is Nil

func EnableLogWithDefaultLogger

func EnableLogWithDefaultLogger()

EnableLogWithDefaultLogger enables logging with fmt.Printf output.

func GetOSEnv

func GetOSEnv() map[string]string

func LoadConfig

func LoadConfig(cfg interface{}) error

func UseStrict

func UseStrict()

UseStrict enables strict mode. in strict mode, all config field must be tagged with "cfg:"

Types

type LogFunc

type LogFunc func(string, ...interface{})

type Options

type Options struct {
	ConfigKey  string
	Slice      bool
	SliceMerge bool
}

type ReflectField

type ReflectField struct {
	Field    reflect.StructField
	RefValue reflect.Value
	Options  Options
}

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL