✨ Load config from TOML
This commit is contained in:
parent
e7b88bcc09
commit
9ddaa98ff4
5 changed files with 47 additions and 7 deletions
|
|
@ -1,16 +1,16 @@
|
|||
package config
|
||||
|
||||
type Config struct {
|
||||
Name string
|
||||
Env Env
|
||||
BaseURL string
|
||||
Conn ConnSettings
|
||||
Name string `toml:"name"`
|
||||
Env Env `toml:"env"`
|
||||
BaseURL string `toml:"base_url"`
|
||||
Conn ConnSettings `toml:"conn"`
|
||||
}
|
||||
|
||||
type ConnSettings struct {
|
||||
Store string
|
||||
DSN string
|
||||
AdditionalSettings map[string]any
|
||||
Store string `toml:"store"`
|
||||
DSN string `toml:"dsn"`
|
||||
Settings map[string]any `toml:"settings"`
|
||||
}
|
||||
|
||||
func (c Config) Environment() Env {
|
||||
|
|
|
|||
8
config/load.go
Normal file
8
config/load.go
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
package config
|
||||
|
||||
import "github.com/BurntSushi/toml"
|
||||
|
||||
func LoadFromToml(path string) (c Config, err error) {
|
||||
_, err = toml.DecodeFile(path, &c)
|
||||
return
|
||||
}
|
||||
29
config/load_test.go
Normal file
29
config/load_test.go
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLoadTomlMissing(t *testing.T) {
|
||||
_, e := LoadFromToml("not-a-real-filee")
|
||||
assert.Error(t, e)
|
||||
}
|
||||
|
||||
func TestLoadTomlGood(t *testing.T) {
|
||||
tmp, _ := os.CreateTemp("", "*.toml")
|
||||
defer tmp.Close()
|
||||
fmt.Fprintln(tmp, `name = "Cool"`)
|
||||
fmt.Fprintln(tmp, "[conn]")
|
||||
fmt.Fprintln(tmp, `store = "sqlite"`)
|
||||
fmt.Fprintln(tmp, "[conn.settings]")
|
||||
fmt.Fprintln(tmp, `num = 42`)
|
||||
c, e := LoadFromToml(tmp.Name())
|
||||
assert.NoError(t, e)
|
||||
assert.Equal(t, "Cool", c.Name)
|
||||
assert.Equal(t, "sqlite", c.Conn.Store)
|
||||
assert.Equal(t, int64(42), c.Conn.Settings["num"])
|
||||
}
|
||||
Reference in a new issue