generated from qiangxue/go-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
64 lines (55 loc) · 1.67 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package config
import (
"github.com/garaekz/priv8/pkg/log"
"github.com/go-ozzo/ozzo-validation/v4"
"github.com/qiangxue/go-env"
"gopkg.in/yaml.v2"
"io/ioutil"
)
const (
defaultServerPort = 8080
defaultJWTExpirationHours = 72
)
// Config represents an application configuration.
type Config struct {
// the server port. Defaults to 8080
ServerPort int `yaml:"server_port" env:"SERVER_PORT"`
// the data source name (DSN) for connecting to the database. required.
DSN string `yaml:"dsn" env:"DSN,secret"`
// JWT signing key. required.
JWTSigningKey string `yaml:"jwt_signing_key" env:"JWT_SIGNING_KEY,secret"`
// JWT expiration in hours. Defaults to 72 hours (3 days)
JWTExpiration int `yaml:"jwt_expiration" env:"JWT_EXPIRATION"`
}
// Validate validates the application configuration.
func (c Config) Validate() error {
return validation.ValidateStruct(&c,
validation.Field(&c.DSN, validation.Required),
validation.Field(&c.JWTSigningKey, validation.Required),
)
}
// Load returns an application configuration which is populated from the given configuration file and environment variables.
func Load(file string, logger log.Logger) (*Config, error) {
// default config
c := Config{
ServerPort: defaultServerPort,
JWTExpiration: defaultJWTExpirationHours,
}
// load from YAML config file
bytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
if err = yaml.Unmarshal(bytes, &c); err != nil {
return nil, err
}
// load from environment variables prefixed with "APP_"
if err = env.New("APP_", logger.Infof).Load(&c); err != nil {
return nil, err
}
// validation
if err = c.Validate(); err != nil {
return nil, err
}
return &c, err
}