Newer
Older
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
/******************** DATA STRUCTS ***********************/
// Player represents a player
type Player struct {
}
// Game represents a game object in the database
type Game struct {
ID int
Player1 Player
Player2 Player
Channels [2]chan string
}
// Move represents a move in the game
type Move struct {
GameID int `json:"game_id"`
MoveData string `json:"move"`
GameOver bool `json:"game_over"`
}
var (
)
/************** MAIN FUNCTION **********************/
func main() {
http.HandleFunc("/", hello)
http.HandleFunc("/move", move)
http.HandleFunc("/create", createGame)
http.HandleFunc("/join", joinGame)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Println("could not start server")
}
}
/************************ HANDLERS ************************/
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Big Tac Toe")
}
func move(w http.ResponseWriter, r *http.Request) {
jsonData := readJsonFromRequest(r)
var move Move
err := json.Unmarshal(jsonData, &move)
if err != nil {
log.Println("could not decode json data into Move struct")
}
game := gameData[move.GameID]
sendChan := game.Channels[move.Player]
recChan := game.Channels[1-move.Player]
sendChan <- move.MoveData
response := <-recChan
fmt.Fprintf(w, response)