100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
package config
|
|
|
|
import (
|
|
"io"
|
|
"io/ioutil"
|
|
|
|
"github.com/caarlos0/env/v6"
|
|
"github.com/pkg/errors"
|
|
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// Config is the configuration struct
|
|
type Config struct {
|
|
HTTP HTTPConfig `yaml:"http"`
|
|
Client ClientConfig `yaml:"client"`
|
|
Data DataConfig `ymal:"data"`
|
|
}
|
|
|
|
// HTTPConfig is the configuration part which defines HTTP related params
|
|
type HTTPConfig struct {
|
|
BaseURL string `yaml:"baseurl" env:"GUESSTIMATE_BASE_URL"`
|
|
Address string `yaml:"address" env:"GUESSTIMATE_HTTP_ADDRESS"`
|
|
PublicDir string `yaml:"publicDir" env:"GUESSTIMATE_PUBLIC_DIR"`
|
|
}
|
|
|
|
// ClientConfig is the configuration part which defines the client app related params
|
|
type ClientConfig struct {
|
|
BaseURL string `yaml:"baseurl" env:"GUESSTIMATE_CLIENT_BASE_URL"`
|
|
Address string `yaml:"address" env:"GUESSTIMATE_CLIENT_HTTP_ADDRESS"`
|
|
}
|
|
|
|
// DataConfig is the configuration part which defines data related params
|
|
type DataConfig struct {
|
|
Path string `yaml:"path" env:"GUESSTIMATE_DATA_PATH"`
|
|
}
|
|
|
|
// NewFromFile retrieves the configuration from the given file
|
|
func NewFromFile(filepath string) (*Config, error) {
|
|
config := NewDefault()
|
|
|
|
data, err := ioutil.ReadFile(filepath)
|
|
if err != nil {
|
|
return nil, errors.Wrapf(err, "could not read file '%s'", filepath)
|
|
}
|
|
|
|
if err := yaml.Unmarshal(data, config); err != nil {
|
|
return nil, errors.Wrapf(err, "could not unmarshal configuration")
|
|
}
|
|
|
|
return config, nil
|
|
}
|
|
|
|
// WithEnvironment retrieves the configuration from env vars
|
|
func WithEnvironment(conf *Config) error {
|
|
if err := env.Parse(conf); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// NewDumpDefault retrieves the default configuration
|
|
func NewDumpDefault() *Config {
|
|
config := NewDefault()
|
|
return config
|
|
}
|
|
|
|
// NewDefault creates and returns a new default configuration
|
|
func NewDefault() *Config {
|
|
return &Config{
|
|
HTTP: HTTPConfig{
|
|
BaseURL: "localhost",
|
|
Address: ":8081",
|
|
PublicDir: "public",
|
|
},
|
|
Client: ClientConfig{
|
|
BaseURL: "localhost",
|
|
Address: ":8080",
|
|
},
|
|
Data: DataConfig{
|
|
Path: "guesstimate.db",
|
|
},
|
|
}
|
|
}
|
|
|
|
// Dump writes a given config to a config file
|
|
func Dump(config *Config, w io.Writer) error {
|
|
data, err := yaml.Marshal(config)
|
|
if err != nil {
|
|
return errors.Wrap(err, "could not dump config")
|
|
}
|
|
|
|
if _, err := w.Write(data); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|