2020-02-19 22:13:06 +01:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2020-07-17 11:45:35 +02:00
|
|
|
"github.com/caarlos0/env/v6"
|
2020-02-19 22:13:06 +01:00
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
2020-07-17 11:45:35 +02:00
|
|
|
Debug bool `yaml:"debug" env:"DEBUG"`
|
2020-07-16 17:01:44 +02:00
|
|
|
HTTP HTTPConfig `yaml:"http"`
|
2020-02-19 22:13:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
|
|
|
type HTTPConfig struct {
|
2020-07-17 11:45:35 +02:00
|
|
|
Address string `yaml:"address" env:"HTTP_ADDRESS"`
|
|
|
|
CookieAuthenticationKey string `yaml:"cookieAuthenticationKey" env:"HTTP_COOKIE_AUTHENTICATION_KEY"`
|
|
|
|
CookieEncryptionKey string `yaml:"cookieEncryptionKey" env:"HTTP_COOKIE_ENCRYPTION_KEY"`
|
|
|
|
CookieMaxAge int `yaml:"cookieMaxAge" env:"HTTP_COOKIE_MAX_AGE"`
|
|
|
|
TemplateDir string `yaml:"templateDir" env:"HTTP_TEMPLATE_DIR"`
|
|
|
|
PublicDir string `yaml:"publicDir" env:"HTTP_PUBLIC_DIR"`
|
2020-02-19 22:13:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewDumpDefault() *Config {
|
|
|
|
config := NewDefault()
|
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewDefault() *Config {
|
|
|
|
return &Config{
|
2020-07-16 17:01:44 +02:00
|
|
|
Debug: false,
|
2020-02-19 22:13:06 +01:00
|
|
|
HTTP: HTTPConfig{
|
|
|
|
Address: ":3000",
|
|
|
|
CookieAuthenticationKey: "",
|
|
|
|
CookieEncryptionKey: "",
|
|
|
|
CookieMaxAge: int((time.Hour * 1).Seconds()), // 1 hour
|
|
|
|
TemplateDir: "template",
|
|
|
|
PublicDir: "public",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2020-07-17 11:45:35 +02:00
|
|
|
|
|
|
|
func WithEnvironment(conf *Config) error {
|
|
|
|
if err := env.Parse(conf); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|