server: Add /api/history/day

master
Luther Wen Xu 2020-04-23 20:55:30 +07:00
parent 237ce4ee2a
commit 6d5d07e2e5
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
2 changed files with 19 additions and 0 deletions

@ -3,12 +3,16 @@ package server
import (
"encoding/json"
"net/http"
"time"
"status/db"
)
func writeJSON(w http.ResponseWriter, a interface{}) {
bytes, err := json.Marshal(a)
if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(bytes)
@ -21,3 +25,17 @@ func allStatus(w http.ResponseWriter, req *http.Request) {
status := getStatus()
writeJSON(w, status)
}
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
}
entries := db.GetFromDB(keys[0], time.Now().Add(time.Duration(-24)*time.Hour), time.Now())
writeJSON(w, entries)
}

@ -8,6 +8,7 @@ import (
func apiEndpoints() {
http.HandleFunc("/api/latest", allStatus)
http.HandleFunc("/api/history/day", dayHistory)
}
func StartServer(port int) {