server: Implement `interval` on /api/history/day

The default value is 5 for interval.
Luther Wen Xu 2020-04-23 22:32:56 +07:00
parent 2560637c21
commit ed0e61cf79
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
1 changed files with 32 additions and 24 deletions

@ -3,6 +3,7 @@ package server
import (
"encoding/json"
"net/http"
"strconv"
"time"
"status/db"
@ -36,39 +37,46 @@ func dayHistory(w http.ResponseWriter, req *http.Request) {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
return
}
entries := db.GetFromDB(keys[0], time.Now().Add(time.Duration(-24)*time.Hour), time.Now())
writeJSON(w, entries)
}
func weekHistory(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)
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)
return
}
if len(keys) >= 2 {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
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
}
entries := getHistoryDay(keys[0], 7)
writeJSON(w, entries)
}
func monthHistory(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)
entries := db.GetFromDB(service_name, time.Now().Add(time.Duration(-24)*time.Hour), time.Now())
if interval == 1 {
writeJSON(w, entries)
return
}
if len(keys) >= 2 {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
return
filteredEntries := make([]db.PingEntry, 0, len(entries)/interval)
for i := 0; i < len(entries); i += interval {
filteredEntries = append(filteredEntries, entries[i])
}
entries := getHistoryDay(keys[0], 31)
writeJSON(w, entries)
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)
@ -78,6 +86,6 @@ func yearHistory(w http.ResponseWriter, req *http.Request) {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
return
}
entries := getHistoryDay(keys[0], 366)
entries := getHistoryDay(keys[0], dayCount)
writeJSON(w, entries)
}