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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
package config
import (
"encoding/json"
"fmt"
"os"
"time"
)
type Config struct {
Server ServerConfig `json:"server"`
Database DatabaseConfig `json:"database"`
Monitor MonitorConfig `json:"monitor"`
SMTP SMTPConfig `json:"smtp"`
Auth AuthConfig `json:"auth"`
}
type SMTPConfig struct {
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
From string `json:"from"`
}
type AuthConfig struct {
AdminUsername string `json:"admin_username"`
AdminPasswordHash string `json:"admin_password_hash"`
JWTSecret string `json:"jwt_secret"`
}
type ServerConfig struct {
Addr string `json:"addr"`
}
type DatabaseConfig struct {
URL string `json:"url"`
}
type MonitorConfig struct {
Interval string `json:"interval"`
Timeout string `json:"timeout"`
}
func Load(path string) (*Config, error) {
if path == "" {
path = "config.json"
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("ler config %s: %w", path, err)
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config %s: %w", path, err)
}
cfg.applyDefaults()
return &cfg, nil
}
func (c *Config) applyDefaults() {
if c.Server.Addr == "" {
c.Server.Addr = ":8080"
}
if c.Monitor.Interval == "" {
c.Monitor.Interval = "60s"
}
if c.Monitor.Timeout == "" {
c.Monitor.Timeout = "10s"
}
}
func (c *Config) ServerAddr() string {
if v := os.Getenv("ADDR"); v != "" {
return v
}
return c.Server.Addr
}
func (c *Config) DatabaseURL() string {
if v := os.Getenv("DATABASE_URL"); v != "" {
return v
}
return c.Database.URL
}
func (c *Config) CheckInterval() time.Duration {
d, err := time.ParseDuration(c.Monitor.Interval)
if err != nil {
return 60 * time.Second
}
return d
}
func (c *Config) CheckTimeout() time.Duration {
d, err := time.ParseDuration(c.Monitor.Timeout)
if err != nil {
return 10 * time.Second
}
return d
}
func (c *Config) AdminUsername() string {
if v := os.Getenv("ADMIN_USERNAME"); v != "" {
return v
}
return c.Auth.AdminUsername
}
func (c *Config) AdminPasswordHash() string {
if v := os.Getenv("ADMIN_PASSWORD_HASH"); v != "" {
return v
}
return c.Auth.AdminPasswordHash
}
func (c *Config) JWTSecret() string {
if v := os.Getenv("JWT_SECRET"); v != "" {
return v
}
return c.Auth.JWTSecret
}
|