server: Fail early for non-existent service name
continuous-integration/drone/push Build is failing Details

master
Luther Wen Xu 2020-05-16 20:04:47 +07:00
parent 2d158a5bd0
commit 99232eb17f
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
4 changed files with 24 additions and 3 deletions

@ -10,5 +10,9 @@ func main() {
panic(err)
}
go checkLoop(cfg.Targets)
server.StartServer(cfg.Port)
validServices := make([]string, 0, len(cfg.Targets))
for _, v := range cfg.Targets {
validServices = append(validServices, v.ServiceName)
}
server.StartServer(cfg.Port, validServices)
}

@ -38,6 +38,10 @@ func dayHistory(w http.ResponseWriter, req *http.Request) {
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 {
@ -89,6 +93,10 @@ func history(w http.ResponseWriter, req *http.Request, dayCount int) {
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)
}

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

@ -6,6 +6,10 @@ import (
"strconv"
)
var (
validTarget = make(map[string]bool)
)
func apiEndpoints() {
http.HandleFunc("/api/latest", allStatus)
http.HandleFunc("/api/history/day", dayHistory)
@ -14,7 +18,10 @@ func apiEndpoints() {
http.HandleFunc("/api/history/year", yearHistory)
}
func StartServer(port int) {
func StartServer(port int, validTargets []string) {
for _, v := range validTargets {
validTarget[v] = true
}
apiEndpoints()
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
if err != nil {