diff --git a/main.go b/main.go index 70dd729..e80b698 100644 --- a/main.go +++ b/main.go @@ -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()) - w.Header().Set("Content-Type", "text/plain") + 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,15 +121,24 @@ 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) + } } } @@ -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))