diff --git a/handlers/high_scores.go b/handlers/high_scores.go new file mode 100644 index 0000000..ba0f081 --- /dev/null +++ b/handlers/high_scores.go @@ -0,0 +1,46 @@ +package handlers + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + + "github.com/gojp/goreportcard/db" + "gopkg.in/mgo.v2/bson" +) + +var highScores []struct { + Repo string + Files int + Average float64 +} + +func HighScoresHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + + db := db.Mongo{URL: mongoURL, Database: mongoDatabase, CollectionName: mongoCollection} + coll, err := db.Collection() + if err != nil { + log.Println("ERROR: could not get collection:", err) + http.Error(w, err.Error(), 500) + return + } + + err = coll.Find(bson.M{"files": bson.M{"$gt": 100}}).Sort("average").All(&highScores) + fmt.Println(highScores) + if err != nil { + log.Println("ERROR: could not get high scores: ", err) + http.Error(w, err.Error(), 500) + return + } + + b, err := json.Marshal(highScores) + if err != nil { + log.Println("ERROR: could not marshal json:", err) + http.Error(w, err.Error(), 500) + return + } + + w.Write(b) +} diff --git a/main.go b/main.go index 873d7de..92addad 100644 --- a/main.go +++ b/main.go @@ -32,6 +32,7 @@ func main() { http.HandleFunc("/checks", handlers.CheckHandler) http.HandleFunc("/report/", makeHandler("report", handlers.ReportHandler)) http.HandleFunc("/badge/", makeHandler("badge", handlers.BadgeHandler)) + http.HandleFunc("/high_scores/", handlers.HighScoresHandler) http.HandleFunc("/", handlers.HomeHandler) fmt.Println("Running on 127.0.01:8080...")