server: Implement /api/history/month and /api/history/year

Luther Wen Xu 2020-04-23 21:49:23 +07:00
parent 84501beb23
commit 2560637c21
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
3 changed files with 33 additions and 3 deletions

@ -50,6 +50,34 @@ func weekHistory(w http.ResponseWriter, req *http.Request) {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest) http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
return return
} }
entries := getWeek(keys[0]) 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)
return
}
if len(keys) >= 2 {
http.Error(w, "Only one `service_name` allowed", http.StatusBadRequest)
return
}
entries := getHistoryDay(keys[0], 31)
writeJSON(w, entries)
}
func yearHistory(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
}
entries := getHistoryDay(keys[0], 366)
writeJSON(w, entries) writeJSON(w, entries)
} }

@ -18,10 +18,10 @@ func getStatus() map[string]db.PingEntry {
return result return result
} }
func getWeek(serviceName string) []stat { func getHistoryDay(serviceName string, dayCount int) []stat {
currentDay := today() currentDay := today()
result := make([]stat, 0) result := make([]stat, 0)
for i := -6; i <= 0; i++ { for i := -dayCount + 1; i <= 0; i++ {
dayData := getDay(serviceName, currentDay.AddDate(0, 0, i)) dayData := getDay(serviceName, currentDay.AddDate(0, 0, i))
if dayData.SampleCount > 0 { if dayData.SampleCount > 0 {
result = append(result, dayData) result = append(result, dayData)

@ -10,6 +10,8 @@ func apiEndpoints() {
http.HandleFunc("/api/latest", allStatus) http.HandleFunc("/api/latest", allStatus)
http.HandleFunc("/api/history/day", dayHistory) http.HandleFunc("/api/history/day", dayHistory)
http.HandleFunc("/api/history/week", weekHistory) http.HandleFunc("/api/history/week", weekHistory)
http.HandleFunc("/api/history/month", monthHistory)
http.HandleFunc("/api/history/year", yearHistory)
} }
func StartServer(port int) { func StartServer(port int) {