Scores can export in json
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
nemunaire 2021-11-19 02:52:54 +01:00
parent edb87a2ff0
commit 860f3eccaa

34
main.go
View File

@ -93,13 +93,25 @@ func ServeChunk(w http.ResponseWriter, r *http.Request) {
}
}
type Score struct {
Login string `json:"login"`
NbChunk int `json:"chunks"`
Time time.Time `json:"time"`
}
func ServeScores(w http.ResponseWriter, r *http.Request) {
if addr := r.Header.Get("X-Forwarded-For"); addr != "" {
r.RemoteAddr = addr
}
log.Printf("Handling %s request from %s: %s [%s]\n", r.Method, r.RemoteAddr, r.URL.Path, r.UserAgent())
isJson := false
if strings.HasSuffix(r.URL.Path, "/scores.json") {
w.Header().Set("Content-Type", "application/json")
isJson = true
} else {
w.Header().Set("Content-Type", "text/plain")
}
if rows, err := DBQuery("SELECT username, COUNT(id_chunk) AS nbchunk, MAX(time) AS time FROM chunks GROUP BY username ORDER BY nbchunk DESC"); err != nil {
w.WriteHeader(http.StatusBadRequest)
@ -109,16 +121,25 @@ func ServeScores(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
for rows.Next() {
var login string
var nbchunk int
var time time.Time
var scores []Score
if err := rows.Scan(&login, &nbchunk, &time); err == nil {
w.Write([]byte(fmt.Sprintf("%q,%d,%q\n", login, nbchunk, time)))
for rows.Next() {
var score Score
if err := rows.Scan(&score.Login, &score.NbChunk, &score.Time); err == nil {
if isJson {
scores = append(scores, score)
} else {
w.Write([]byte(fmt.Sprintf("%q,%d,%q\n", score.Login, score.NbChunk, score.Time)))
}
}
}
if isJson {
res, _ := json.Marshal(scores)
w.Write(res)
}
}
}
func main() {
@ -147,6 +168,7 @@ func main() {
log.Println("Registering handlers...")
http.HandleFunc("/scores", ServeScores)
http.HandleFunc("/scores.json", ServeScores)
http.HandleFunc("/chunk", ServeChunk)
log.Println(fmt.Sprintf("Ready, listening on %s", *bind))