diff --git a/config.go b/config.go index d2a8d39..4602a1a 100644 --- a/config.go +++ b/config.go @@ -7,6 +7,7 @@ import ( type Config struct { Targets []checkTarget + Port int } func ReadConfig(file string) (Config, error) { diff --git a/main.go b/main.go index c586cd7..baa102c 100644 --- a/main.go +++ b/main.go @@ -1,9 +1,14 @@ package main +import ( + "status/server" +) + func main() { cfg, err := ReadConfig("config.json") if err != nil { panic(err) } - checkLoop(cfg.Targets) + go checkLoop(cfg.Targets) + server.StartServer(cfg.Port) } diff --git a/server/api.go b/server/api.go new file mode 100644 index 0000000..270a186 --- /dev/null +++ b/server/api.go @@ -0,0 +1,20 @@ +package server + +import ( + "encoding/json" + "net/http" +) + +func writeJSON(w http.ResponseWriter, a interface{}) { + bytes, err := json.Marshal(a) + if err != nil { + http.Error(w, "500 Internal Server Error", http.StatusInternalServerError) + } + w.Header().Set("Content-Type", "application/json") + w.Write(bytes) +} + +func allStatus(w http.ResponseWriter, req *http.Request) { + status := getStatus() + writeJSON(w, status) +} diff --git a/server/cache.go b/server/cache.go new file mode 100644 index 0000000..84661db --- /dev/null +++ b/server/cache.go @@ -0,0 +1,19 @@ +package server + +import ( + "time" + + "status/db" +) + +func getStatus() map[string]db.PingEntry { + entries := db.GetFromDB("", time.Now().Add(time.Duration(-2)*time.Minute), time.Now()) + result := make(map[string]db.PingEntry) + for _, v := range entries { + if v.Time.Before(result[v.ServiceName].Time) { + continue + } + result[v.ServiceName] = v + } + return result +} diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..9c1fb84 --- /dev/null +++ b/server/server.go @@ -0,0 +1,19 @@ +package server + +import ( + "fmt" + "net/http" + "strconv" +) + +func apiEndpoints() { + http.HandleFunc("/api/latest", allStatus) +} + +func StartServer(port int) { + apiEndpoints() + err := http.ListenAndServe(":"+strconv.Itoa(port), nil) + if err != nil { + fmt.Printf("ListenAndServe returned an error: %v", err) + } +}