-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
105 lines (95 loc) · 2.29 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/gmemstr/platypus/common"
"github.com/gmemstr/platypus/router"
"github.com/gmemstr/platypus/stats"
"github.com/go-yaml/yaml"
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
GenFiles()
file, err := ioutil.ReadFile("config.yml")
if err != nil {
panic(err)
}
err = yaml.Unmarshal(file, &common.Config)
if err != nil {
panic(err)
}
// Repopulate servers from cache file.
statsCache, err := ioutil.ReadFile("stats.json")
if err != nil {
panic(err)
}
err = json.Unmarshal(statsCache, &stats.Servers)
if err != nil {
panic(err)
}
// Cache server stats in event master goes down.
defer func() {
jsonServers, err := json.MarshalIndent(stats.Servers, "", " ")
if err != nil {
panic(err)
}
err = ioutil.WriteFile("stats.json", jsonServers, 0644)
if err != nil {
panic(err)
}
}()
// Start up server.
r := router.Init()
fmt.Println("Your Platytpus instance is live on port :9090")
log.Fatal(http.ListenAndServe(":9090", r))
}
// Generate barebones files required to run.
func GenFiles() {
if _, err := os.Stat(".secret"); os.IsNotExist(err) {
fmt.Println("Generating secret key to .secret, use this to configure your servers")
SecretKey()
}
if _, err := os.Stat("stats.json"); os.IsNotExist(err) {
err = ioutil.WriteFile("stats.json", []byte("{}"), 0644)
if err != nil {
panic(err)
}
}
if _, err := os.Stat("config.yml"); os.IsNotExist(err) {
err = ioutil.WriteFile("config.yml", []byte("port: 9090\ninterval: 5\n"), 0644)
if err != nil {
panic(err)
}
}
}
func SecretKey() {
key, err := GenerateRandomString(32)
if err != nil {
panic(err)
}
err = ioutil.WriteFile(".secret", []byte(key), 0644)
if err != nil {
panic(err)
}
}
// From https://stackoverflow.com/questions/32349807/how-can-i-generate-a-random-int-using-the-crypto-rand-package
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}
// GenerateRandomString returns a URL-safe, base64 encoded
// securely generated random string.
func GenerateRandomString(s int) (string, error) {
b, err := GenerateRandomBytes(s)
return hex.EncodeToString(b), err
}