forked from smacfarlane/mapwrap-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
96 lines (81 loc) · 1.84 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
package main
import (
"bytes"
"encoding/json"
"io"
"log"
"os"
"os/exec"
"path/filepath"
)
type Config struct {
Environment []string
Mapserv string
Port string
Directory string
Maps []Map
}
const defaultConfig = `
{
"environment": [],
"port": "8080"
}
`
var config *Config
func GetConfig() *Config {
return config
}
func loadConfig() {
var temp Config
if err := decodeConfig(bytes.NewBufferString(defaultConfig), &temp); err != nil {
log.Fatal(err)
}
//Look for a configuration file in the following order:
// Environment: MAPWRAP_CONFIG
// Current Directory: mapwrap.json
configFile := os.Getenv("MAPWRAP_CONFIG")
if configFile == "" {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
configFile = filepath.Join(cwd, "mapwrap.json")
}
f, err := os.Open(configFile)
defer f.Close()
if err != nil {
log.Printf("Error opening configuration file: %s\n", configFile)
log.Fatal(err)
}
if err := decodeConfig(f, &temp); err != nil {
log.Printf("Error loading configuration file: %s\n", configFile)
log.Fatal(err)
}
//Set the working directory if it's not already set
if temp.Directory == "" {
temp.Directory, err = os.Getwd()
if err != nil {
log.Fatal(err)
}
}
//Make sure the directory exists
_, err = os.Stat(temp.Directory)
if err != nil {
log.Fatal(err)
}
if temp.Mapserv == "" {
temp.Mapserv = "mapserv"
}
_, err = exec.Command(temp.Mapserv).Output()
if err != nil {
log.Fatal("Error attempting to run mapserv: ", err)
}
config = &temp
log.Println("[INFO] Config loaded")
}
// Decodes configuration in JSON format from the given io.Reader into
// the config object pointed to.
func decodeConfig(r io.Reader, c *Config) error {
decoder := json.NewDecoder(r)
return decoder.Decode(c)
}