scaffold-goweb/internal/config/config.go

83 lines
1.9 KiB
Go
Raw Permalink Normal View History

2020-02-19 22:13:06 +01:00
package config
import (
"io"
"io/ioutil"
"time"
"github.com/pkg/errors"
"github.com/caarlos0/env/v6"
2020-02-19 22:13:06 +01:00
"gopkg.in/yaml.v2"
)
type Config struct {
Debug bool `yaml:"debug" env:"DEBUG"`
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 {
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{
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
}
func WithEnvironment(conf *Config) error {
if err := env.Parse(conf); err != nil {
return err
}
return nil
}