server/control.go

94 lines
1.9 KiB
Go

package main
import (
"encoding/json"
"log"
"net/http"
"runtime/pprof"
"strings"
)
type JsonHandler func(http.ResponseWriter, *http.Request)
func (h JsonHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
h(w, req)
}
func startGame(w http.ResponseWriter, req *http.Request) {
new_game_name := idg.Hash()
_g := NewGame(new_game_name, *width, *height)
go _g.run()
games.Lock()
games.m[new_game_name] = _g
games.Unlock()
game_json := struct {
Id string `json:"id"`
}{
Id: new_game_name,
}
if err := json.NewEncoder(w).Encode(game_json); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func listGames(w http.ResponseWriter, req *http.Request) {
games.RLock()
defer games.RUnlock()
type pout struct {
Name string `json:"name"`
Id string `json:"id"`
}
type gl struct {
Id string `json:"id"`
Players []pout `json:"players"`
}
ids := make([]gl, 0)
for id, g := range games.m {
players := make([]pout, 0)
for p, _ := range g.players {
players = append(players, pout{
Name: p.Robot.Name,
Id: p.Robot.Id,
})
}
ids = append(ids, gl{
Id: id,
Players: players,
})
}
if err := json.NewEncoder(w).Encode(ids); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func stopGame(w http.ResponseWriter, req *http.Request) {
trimmed := strings.Trim(req.URL.Path, "/")
fullPath := strings.Split(trimmed, "/")
if len(fullPath) != 3 {
http.Error(w, "improperly formed url", http.StatusBadRequest)
return
}
key := fullPath[2]
games.Lock()
gameid, ok := games.m[key]
defer games.Unlock()
if !ok {
http.NotFound(w, req)
return
}
gameid.kill <- true
}
func killServer(w http.ResponseWriter, req *http.Request) {
if *profile != "" {
log.Print("trying to stop cpu profile")
pprof.StopCPUProfile()
log.Print("stopped cpu profile")
}
log.Fatal("shit got fucked up")
}