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) if err != nil { http.Error(w, "500 Internal Server Error", http.StatusInternalServerError) } } 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) } 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) return } if len(keys) >= 2 { http.Error(w, "Only one `service_name` allowed", 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) 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) }