/
main.go
82 lines (71 loc) · 1.6 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"strings"
"github.com/spf13/viper"
)
var API_VERSION = "/1"
var inits []func()
func readKernelConfig() {
cmdline, err := ioutil.ReadFile("/proc/cmdline")
if err != nil {
panic(fmt.Sprint("Error opening /proc/cmdline:", err.Error()))
}
options := strings.Split(strings.TrimSpace(string(cmdline)), " ")
for _, option := range options {
kv := strings.SplitN(option, "=", 2)
if len(kv) < 2 {
continue
}
if kv[0][0:4] == "pcd." {
viper.Set(kv[0], kv[1])
} else if kv[0] == "hostname" {
viper.Set(kv[0], kv[1])
}
}
}
func saveConfig() {
cmd := exec.Command("mount", "LABEL=BOOT", "/boot")
err := cmd.Run()
if err != nil {
return
}
b, _ := json.MarshalIndent(viper.AllSettings(), "", " ")
err = ioutil.WriteFile(viper.GetString("file"), b, 0644)
if err != nil {
panic(fmt.Sprint("Error opening file:", err.Error()))
}
fmt.Println("Config saved.")
cmd = exec.Command("umount", "/boot")
cmd.Run()
}
func runHandlers() {
for init := range inits {
inits[init]()
}
}
func main() {
viper.SetDefault("file", "/boot/config.json")
readKernelConfig()
viper.SetConfigFile(viper.GetString("file"))
cmd := exec.Command("mount", "LABEL=BOOT", "/boot")
err := cmd.Run()
if err == nil {
err = viper.ReadInConfig()
cmd = exec.Command("umount", "/boot")
cmd.Run()
if err != nil {
fmt.Println("Error reading config file: ", err.Error())
}
saveConfig()
} else {
fmt.Println(err.Error())
}
runHandlers()
fmt.Println("Starting http server on :8080")
http.ListenAndServe("127.0.0.1:8080", nil)
}