forked from Team-Ortix/StatusApp
server: Add HTTP server
parent
5f14a5b943
commit
81e74807f4
@ -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)
|
||||
}
|
||||
|
@ -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)
|
||||
}
|
@ -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
|
||||
}
|
@ -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)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue