Validate the runtime environment against given JSON schema.
import (
"github.com/aereal/go-envschema/loader"
"github.com/xeipuuv/gojsonschema"
)
type config struct {
Addr string `json:"LISTEN_ADDR"`
}
func run() error {
// LISTEN_ADDR=localhost:8000
loader, err := loader.New(gojsonschema.NewReferenceLoader("file://./config-schema.json"))
if err != nil {
return err
}
cfg := config{}
if err := loader.Load(&cfg); err != nil {
return err
}
// cfg.Addr // => "localhost:8000"
return nil
}
The Twelve-Factor app that is container-aware application pattern mainly written by Heroku says the twelve-factor app stores config in environment variables
.
That pattern is almost alive to this days but that is lacking in validation system in comparison with common config file pattern.
So all we need is validating the environment variables against the schema and mapping it into runtime structure mechanism.
refs. https://this.aereal.org/entry/container-apps-and-json-schema (Blog entry in Japanese)
- go-playground/validator: focused on validating struct, no environment mapping