StatusApp/server/api.go

95 lines
2.4 KiB
Go

2020-04-23 07:42:16 +07:00
package server
import (
"encoding/json"
"net/http"
"strconv"
2020-04-23 12:55:30 +07:00
"time"
"status/db"
2020-04-23 07:42:16 +07:00
)
func writeJSON(w http.ResponseWriter, a interface{}) {
bytes, err := json.Marshal(a)
if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
2020-04-23 12:55:30 +07:00
return
2020-04-23 07:42:16 +07:00
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(bytes)
if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
}
2020-04-23 07:42:16 +07:00
}
func allStatus(w http.ResponseWriter, req *http.Request) {
status := getStatus()
writeJSON(w, status)
}
2020-04-23 12:55:30 +07:00
func dayHistory(w http.ResponseWriter, req *http.Request) {
keys, ok := req.URL.Query()["service_name"]
if !ok || len(keys) == 0 || len(keys[0]) < 1 {
http.Error(w, "`service_name` not provided", http.StatusBadRequest)
return
}
if len(keys) >= 2 {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
return
}
service_name := keys[0]
keys, ok = req.URL.Query()["interval"]
var interval = 5
if len(keys) >= 2 {
http.Error(w, "Only one `interval` allowed", http.StatusBadRequest)
2020-04-23 13:44:23 +07:00
return
}
if ok && len(keys) == 1 && len(keys[0]) >= 1 {
var err error
interval, err = strconv.Atoi(keys[0])
if err != nil || interval < 1 || interval > 1440 {
http.Error(w, "Invalid `interval` provided. Must be integer in [1, 1440]", http.StatusBadRequest)
return
}
}
2020-04-23 15:32:10 +07:00
if service_name == "all" {
service_name = ""
}
entries := db.GetFromDB(service_name, time.Now().Add(time.Duration(-24)*time.Hour), time.Now())
if interval == 1 {
writeJSON(w, entries)
2020-04-23 13:44:23 +07:00
return
}
filteredEntries := make([]db.PingEntry, 0, len(entries)/interval)
for i := 0; i < len(entries); i += interval {
filteredEntries = append(filteredEntries, entries[i])
}
writeJSON(w, filteredEntries)
}
func weekHistory(w http.ResponseWriter, req *http.Request) {
history(w, req, 7)
}
func monthHistory(w http.ResponseWriter, req *http.Request) {
history(w, req, 31)
}
func yearHistory(w http.ResponseWriter, req *http.Request) {
history(w, req, 366)
}
func history(w http.ResponseWriter, req *http.Request, dayCount int) {
keys, ok := req.URL.Query()["service_name"]
if !ok || len(keys) == 0 || len(keys[0]) < 1 {
http.Error(w, "`service_name` not provided", http.StatusBadRequest)
return
}
if len(keys) >= 2 {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
return
}
entries := getHistoryDay(keys[0], dayCount)
2020-04-23 13:44:23 +07:00
writeJSON(w, entries)
}