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.WriteString(" \"")
json.WriteString(name)
json.WriteString("\": {\n")
sorted := sortByValue(top)
for i, key := range sorted {
fmt.Fprintf(json, " \"%s\": %d", key, top[key]))
if i+1 != len(sorted) {
json.WriteByte(',')
} }
json, err := json.Marshal(toMarshal) json.WriteByte('\n')
if err != nil {
errortext := fmt.Sprintf("Couldn't marshal into JSON: %s", err)
log.Println(errortext)
http.Error(w, errortext, http.StatusBadGateway)
return
} }
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)