/
config.go
100 lines (85 loc) · 2 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
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
package main
import (
"fmt"
"os"
"strings"
"github.com/zerozwt/swe"
"gopkg.in/yaml.v3"
)
type ConfigService struct {
Core bool `yaml:"core"`
Collector bool `yaml:"collector"`
}
type LogConfig struct {
Level string `yaml:"level"`
File string `yaml:"file"`
}
type Config struct {
LocalHost bool `yaml:"localhost"`
Port uint16 `yaml:"port"`
DbEngine string `yaml:"db_engine"`
MySQL string `yaml:"mysql"`
SQLite string `yaml:"sqlite"`
WebDir string `yaml:"www_dir"`
Service ConfigService `yaml:"service"`
Etcd []string `yaml:"etcd"`
Log LogConfig `yaml:"log"`
}
func (c Config) IsMySQL() bool { return c.DbEngine == "mysql" }
func (c Config) IsSQLite() bool { return c.DbEngine == "sqlite" }
func (c Config) LogLevel() swe.LogLevel {
switch c.Log.Level {
case "debug":
return swe.LOG_DEBUG
case "info":
return swe.LOG_INFO
case "warn":
return swe.LOG_WARN
case "error":
return swe.LOG_ERROR
}
return swe.LOG_INFO
}
func (c Config) WebAddr() string {
if c.LocalHost {
return "localhost:" + fmt.Sprint(c.Port)
}
return ":" + fmt.Sprint(c.Port)
}
var gConfig Config = Config{
LocalHost: true,
Port: 6080,
DbEngine: "sqlite",
SQLite: "./octant.db",
WebDir: "./dist",
Service: ConfigService{
Core: true,
Collector: true,
},
Log: LogConfig{
Level: "debug",
File: "",
},
}
func LoadConfig(file string) error {
confData, err := os.ReadFile(file)
if err != nil {
return err
}
err = yaml.Unmarshal(confData, &gConfig)
if err != nil {
return err
}
gConfig.DbEngine = strings.ToLower(gConfig.DbEngine)
if gConfig.Port == 0 {
return fmt.Errorf("invalid port %d", gConfig.Port)
}
if gConfig.DbEngine != "sqlite" && gConfig.DbEngine != "mysql" {
return fmt.Errorf("invalid db engine: %s", gConfig.DbEngine)
}
if !(gConfig.Service.Core || gConfig.Service.Collector) {
return fmt.Errorf("no service")
}
gConfig.Log.Level = strings.ToLower(gConfig.Log.Level)
return nil
}