added simple game stats

This commit is contained in:
sm
2013-11-13 23:45:02 -08:00
parent 84ed6c9c32
commit 245c483f9e
4 changed files with 84 additions and 29 deletions
+47 -8
View File
@@ -2,6 +2,8 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
@@ -105,23 +107,49 @@ func listGames(w http.ResponseWriter, req *http.Request) {
}
}
func stopGame(w http.ResponseWriter, req *http.Request) {
trimmed := strings.Trim(req.URL.Path, "/")
fullPath := strings.Split(trimmed, "/")
log.Println(req.URL.Path)
if len(fullPath) != 3 {
func gameStats(w http.ResponseWriter, req *http.Request) {
key, err := getGameId(req.URL.Path)
if err != nil {
http.Error(w, "improperly formed url", http.StatusBadRequest)
}
log.Printf("requested stats for game: %s", key)
games.RLock()
g, ok := games.m[key]
games.RUnlock()
if !ok {
http.NotFound(w, req)
return
}
key := fullPath[2]
g.winners.RLock()
defer g.winners.RUnlock()
if err := json.NewEncoder(w).Encode(g.winners.m); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func stopGame(w http.ResponseWriter, req *http.Request) {
key, err := getGameId(req.URL.Path)
if err != nil {
http.Error(w, "improperly formed url", http.StatusBadRequest)
}
games.Lock()
gameid, ok := games.m[key]
g, ok := games.m[key]
defer games.Unlock()
if !ok {
http.NotFound(w, req)
return
}
gameid.kill <- true
g.kill <- true
message := struct {
Ok bool `json:"ok"`
Message string `json:"message"`
}{
Ok: true,
Message: fmt.Sprintf("Successfully stopped game: %s", key),
}
if err := json.NewEncoder(w).Encode(message); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func killServer(w http.ResponseWriter, req *http.Request) {
@@ -146,3 +174,14 @@ func index(w http.ResponseWriter, req *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func getGameId(path string) (string, error) {
var err error
trimmed := strings.Trim(path, "/")
fullPath := strings.Split(trimmed, "/")
if len(fullPath) != 3 {
return "", errors.New("improperly formed url")
}
key := fullPath[2]
return key, err
}