config settings, overridable by settings.go or env (SCOPES_...) settings

This commit is contained in:
Helmut Merz 2023-06-02 09:31:37 +02:00
parent 968bdc925d
commit f896adfb8c
7 changed files with 40 additions and 7 deletions

View file

@ -1,6 +1,11 @@
package config
import "git.sr.ht/~cco/go-scopes/common"
import (
"os"
"strings"
"git.sr.ht/~cco/go-scopes/common"
)
type Cfg struct {
*Base
@ -51,3 +56,17 @@ func MakeBase(name string, starter common.StartFct) *Base {
func Setup(cfg Config) Config {
return cfg
}
// overridable settings
type Settings map[string]string
func (s Settings) Get(key, def string) string {
if v, ok := os.LookupEnv("SCOPES_" + strings.ToUpper(key)); ok {
return v
}
if v, ok := s[key]; ok {
return v
}
return def
}

View file

@ -6,9 +6,11 @@ import (
)
func Config() config.Config {
ovr := Overrides().Get
b := config.MakeBase
cfg := scopes.Cfg{
Base: b("dummy", scopes.Start),
Home: ovr(HOME, "."),
AppType: "standard",
}
cfg.Add(config.Cfg{b("config", config.Start), "etc"})
@ -17,4 +19,5 @@ func Config() config.Config {
const (
NAME = "name"
HOME = "home"
)

View file

@ -1,7 +1,10 @@
package etc
func Override() map[string]string {
return map[string]string{
import "git.sr.ht/~cco/go-scopes/config"
func Overrides() config.Settings {
return config.Settings{
NAME: "overridden",
HOME: "/home/scopes/app",
}
}

View file

@ -10,8 +10,9 @@ import (
)
func main() {
fmt.Println(etc.Override()["name"])
cfg := config.Setup(etc.Config())
fmt.Println(cfg.Name())
appCfg := cfg.(*scopes.Cfg)
fmt.Println(appCfg.Home)
scopes.RunApp(cfg)
}

View file

@ -8,6 +8,7 @@ import (
type Cfg struct {
*config.Base
AppType string
Home string
}
func Start(ctx common.Context) {

View file

@ -6,9 +6,11 @@ import (
)
func Config() config.Config {
ovr := Overrides().Get
b := config.MakeBase
cfg := scopes.Cfg{
Base: b("dummy", scopes.Start),
Home: ovr(HOME, "."),
AppType: "standard",
}
cfg.Add(config.Cfg{b("config", config.Start), "etc"})
@ -19,12 +21,14 @@ func Config() config.Config {
// explicit Override() or SCOPES_* environment settings.
const (
NAME = "name"
HOME = "home"
)
// in a production scenario this should be put in separate
// file `settings.go` that should not be stored in code repository.
func Override() map[string]string {
return map[string]string{
func Overrides() config.Settings {
return config.Settings{
NAME: "overridden",
HOME: "/home/scopes",
}
}

View file

@ -15,8 +15,10 @@ func TestConfig(tb *tbase.T) {
}
func ConfigTest(t *testing.T) {
t.AssertEqual(etc.Override()[etc.NAME], "overridden")
t.AssertEqual(etc.Overrides()[etc.NAME], "overridden")
cfg := config.Setup(etc.Config())
t.AssertEqual(cfg.Name(), "dummy")
appCfg := cfg.(*scopes.Cfg)
t.AssertEqual(appCfg.Home, "/home/scopes")
scopes.RunApp(cfg)
}