gigibox
2023-06-08 5591716c1295f7433f8df797479a73eed4288e2a
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
package config
 
import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)
 
type Config struct {
    WebPort     string `json:"web_port"`
    SqlAddr     string `json:"sql_addr"`
    SqlDBName   string `json:"sql_db_name"`
    SqlUsername string `json:"sql_username"`
    SqlPassword string `json:"sql_password"`
}
 
const configPath = "config.json"
 
var Options Config
 
// Init is an exported method that takes the environment starts the viper
// (external lib) and returns the configuration struct.
func init() {
}
 
func Load() {
    if !pathExists(configPath) {
        SaveConfig()
    } else {
        file, _ := os.Open(configPath)
        defer file.Close()
 
        fd := json.NewDecoder(file)
 
        fd.Decode(&Options)
 
        fmt.Printf("%v\n", Options)
    }
}
 
func SaveConfig() error {
    b, err := json.Marshal(Options)
    if err == nil {
        var out bytes.Buffer
        err = json.Indent(&out, b, "", "    ")
        ioutil.WriteFile(configPath, out.Bytes(), 0644)
    }
 
    return err
}
 
func pathExists(path string) bool {
    _, err := os.Stat(path)
    if err == nil {
        return true
    }
 
    fmt.Printf("%v", err.Error())
    return false
}