-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
100 lines (78 loc) · 2.16 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
package main
import (
"embed"
"fmt"
"io/fs"
"net/http"
"os"
"os/exec"
"sync"
"time"
kingpin "github.com/alecthomas/kingpin/v2"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
//go:embed ui/dist
var embeddedFS embed.FS
var (
region = "eu-west-1"
config *Config
configM = &sync.Mutex{}
awsSession *session.Session
sessionM = &sync.Mutex{}
accountStates = map[string]*AccountState{}
accountStatesM = &sync.Mutex{}
messages = []Message{}
messagesM = &sync.Mutex{}
)
var (
configFilename = kingpin.Flag("config-file", "Config filename").Short('c').Default("config.json").String()
port = kingpin.Flag("port", "Server port").Short('p').Default("8000").Int32()
refreshInterval = kingpin.Flag("refresh-interval", "Refresh interval (seconds)").Short('r').Default("30").Int()
openBrowser = kingpin.Flag("open", "Open browser").Bool()
)
func main() {
kingpin.Parse()
region = os.Getenv("AWS_REGION")
if region == "" {
region = "eu-west-1"
}
uiFiles, err := fs.Sub(embeddedFS, "ui/dist")
if err != nil {
panic(err)
}
updateConfig(*configFilename)
go watchConfig(*configFilename)
awsConfig := aws.Config{Region: aws.String(region)}
awsSession = session.New(&awsConfig)
go doEvery(time.Duration(*refreshInterval)*time.Second, updateAccounts)
r := mux.NewRouter()
r.HandleFunc("/config", func(w http.ResponseWriter, r *http.Request) {
jsonify(w, config)
})
r.HandleFunc("/api/overview", func(w http.ResponseWriter, r *http.Request) {
result := []*AccountState{}
for _, value := range accountStates {
result = append(result, value)
}
jsonify(w, map[string]interface{}{
"state": result,
"accounts": config.Accounts,
"messages": messages,
})
})
r.PathPrefix("/").Handler(http.FileServer(http.FS(uiFiles)))
cors := handlers.AllowedOrigins([]string{"*"})
if *openBrowser {
go func() {
<-time.After(1000 * time.Millisecond)
exec.Command("xdg-open", fmt.Sprintf("http://localhost:%d", *port)).Run()
}()
}
err = http.ListenAndServe(fmt.Sprintf(":%d", *port), handlers.CORS(cors)(r))
if err != nil {
fmt.Println(err)
}
}