2021-09-11 23:06:03 +01:00
|
|
|
package model
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
|
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
DefaultPort = 8080
|
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
DatabasePath *string `yaml:"database_path"`
|
|
|
|
Port *int `yaml:"port"`
|
2021-09-13 09:06:57 +01:00
|
|
|
Secret *string `yaml:"secret"`
|
2021-09-11 23:06:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Config) SetDefaults() {
|
|
|
|
if c.Port == nil {
|
|
|
|
c.Port = NewInt(DefaultPort)
|
|
|
|
}
|
2021-09-13 09:06:57 +01:00
|
|
|
|
|
|
|
if c.Secret == nil {
|
|
|
|
c.Secret = NewString(NewUUID())
|
|
|
|
}
|
2021-09-11 23:06:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Config) IsValid() error {
|
|
|
|
if c.DatabasePath == nil || *c.DatabasePath == "" {
|
|
|
|
return fmt.Errorf("database_path cannot be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.Port == nil || *c.Port == 0 {
|
|
|
|
return fmt.Errorf("port cannot be empty")
|
|
|
|
}
|
|
|
|
|
2021-09-13 09:06:57 +01:00
|
|
|
if c.Secret == nil || *c.Secret == "" {
|
|
|
|
return fmt.Errorf("secret cannot be empty")
|
|
|
|
}
|
|
|
|
|
2021-09-11 23:06:03 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func ReadConfig(path string) (*Config, error) {
|
|
|
|
b, err := ioutil.ReadFile(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var config Config
|
|
|
|
if err := yaml.Unmarshal(b, &config); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-09-13 09:06:57 +01:00
|
|
|
config.SetDefaults()
|
|
|
|
|
2021-09-11 23:06:03 +01:00
|
|
|
return &config, nil
|
|
|
|
}
|