API /stats_top -- sort top entries by value

This commit is contained in:
Eugene Bujak 2018-09-07 17:50:03 +03:00
parent 8198b65f29
commit f623c3d909

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
@ -438,21 +439,35 @@ func handleStatsTop(w http.ResponseWriter, r *http.Request) {
} }
} }
toMarshal := map[string]interface{}{ // use manual json marshalling because we want maps to be sorted by value
"top_queried_domains": produceTop(domains, 50), json := bytes.Buffer{}
"top_blocked_domains": produceTop(blocked, 50), json.WriteString("{\n")
"top_clients": produceTop(clients, 50),
} gen := func(json *bytes.Buffer, name string, top map[string]int, addComma bool) {
json, err := json.Marshal(toMarshal) json.WriteString(" \"")
if err != nil { json.WriteString(name)
errortext := fmt.Sprintf("Couldn't marshal into JSON: %s", err) json.WriteString("\": {\n")
log.Println(errortext) sorted := sortByValue(top)
http.Error(w, errortext, http.StatusBadGateway) for i, key := range sorted {
return fmt.Fprintf(json, " \"%s\": %d", key, top[key]))
if i+1 != len(sorted) {
json.WriteByte(',')
}
json.WriteByte('\n')
}
json.WriteString(" }")
if addComma {
json.WriteByte(',')
}
json.WriteByte('\n')
} }
gen(&json, "top_queried_domains", domains, true)
gen(&json, "top_blocked_domains", blocked, true)
gen(&json, "top_clients", clients, false)
json.WriteString("}\n")
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, err = w.Write(json) _, err = w.Write(json.Bytes())
if err != nil { if err != nil {
errortext := fmt.Sprintf("Couldn't write body: %s", err) errortext := fmt.Sprintf("Couldn't write body: %s", err)
log.Println(errortext) log.Println(errortext)