This repository has been archived by the owner on Jan 16, 2022. It is now read-only.
/
config.go
75 lines (66 loc) · 2.12 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
package http_util
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/rs/zerolog/log"
)
// ServerConfig is the general struct holds parsed JSON config info
type ServerConfig struct {
Host string `json:"host"`
Port string `json:"port"`
IP string `json:"IP"`
ChooseIP bool `json:"chooseIP"`
HTTPS bool `json:"secure"`
DebugLog bool `json:"debugLog"`
CacheMaxAge int `json:"cacheMaxAge"`
ShutdownCode int `json:"shutdownCode"`
UserShutdown bool `json:"userShutdown"`
CertFile string `json:"certFile"`
KeyFile string `json:"keyFile"`
RootCA string `json:"rootCA"`
// TODO add more
}
// errors declarations
var ErrConfigNotJSON = errors.New("config file not JSON")
// LoadConfig returns a config struct given a valid config.json file
func LoadConfig(filename string) (ServerConfig, error) {
cfg := ServerConfig{}
filePath := filepath.Clean(filename)
cfgFile, err := os.Open(filePath)
if err != nil {
return ServerConfig{}, os.ErrNotExist
}
defer func() {
err := cfgFile.Close()
if err != nil {
log.Error().Err(err).Str("filename", filePath).Msg("error closing the file")
}
}()
jsonParser := json.NewDecoder(cfgFile)
err = jsonParser.Decode(&cfg)
if err != nil {
return ServerConfig{},
ErrConfigNotJSON
}
return cfg, nil
}
// Print provides a pretty formatted print of a ServerConfig
func (cfg *ServerConfig) Print() {
fmt.Printf("\n-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n")
fmt.Printf("ServerConfig:\n")
fmt.Printf("\tHost:\t\t%v\n", cfg.Host)
fmt.Printf("\tPort:\t\t%v\n", cfg.Port)
fmt.Printf("\tIP:\t\t%v\n", cfg.IP)
fmt.Printf("\tChooseIP:\t%t\n", cfg.ChooseIP)
fmt.Printf("\tHTTPS:\t\t%t\n", cfg.HTTPS)
fmt.Printf("\tDebugLog:\t%t\n", cfg.DebugLog)
fmt.Printf("\tDebugLog:\t%t\n", cfg.DebugLog)
fmt.Printf("\tShutdownCode:\t%d\n", cfg.ShutdownCode)
fmt.Printf("\tCertFile:\t%v\n", cfg.CertFile)
fmt.Printf("\tKeyFile:\t%v\n", cfg.KeyFile)
fmt.Printf("\tRootCA:\t\t%v\n", cfg.RootCA)
fmt.Printf("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-\n\n")
}