package server import ( "encoding/json" "net/http" "strconv" "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 } service_name := keys[0] if !validTarget[service_name] { http.Error(w, "Invalid `service_name` requested", http.StatusBadRequest) return } keys, ok = req.URL.Query()["interval"] var interval = 5 if len(keys) >= 2 { http.Error(w, "Only one `interval` allowed", http.StatusBadRequest) 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 } } 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) 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 } if !validTarget[keys[0]] { http.Error(w, "Invalid `service_name` requested", http.StatusBadRequest) return } entries := getHistoryDay(keys[0], dayCount) writeJSON(w, entries) }