added protocol

This commit is contained in:
Stephen McQuay 2013-08-19 20:42:28 -07:00
parent 2c0302210b
commit c46027cfdb
2 changed files with 121 additions and 0 deletions

76
protocol/protocol.go Normal file
View File

@ -0,0 +1,76 @@
package protocol
// > identify
type IdRequest struct {
Type string `json:"type"`
AssignedID string `json:"id"`
}
func NewIdRequest(id string) *IdRequest {
return &IdRequest{
Type: "idreq",
AssignedID: id,
}
}
// < [robot | spectator], name, client-type, game ID
type ClientID struct {
Type string `json:"type"`
Name string `json:"name"`
Useragent string `json:"useragent"`
}
func (c *ClientID) Valid() (bool, string) {
switch c.Type {
case "robot", "spectator":
return true, ""
}
return false, "usergent must be 'robot' or 'spectator'"
}
type BoardSize struct {
Width float64 `json:"width"`
Height float64 `json:"height"`
}
type GameParam struct {
BoardSize BoardSize `json:"boardsize"`
Type string `json:"type"`
}
// > [OK | FULL | NOT AUTH], board size, game params
func NewGameParam(w, h float64) *GameParam {
return &GameParam{
BoardSize: BoardSize{
Width: w,
Height: h,
},
Type: "gameparam",
}
}
type Handshake struct {
ID string `json:"id"`
Success bool `json:"success"`
Type string `json:"type"`
}
func NewHandshake(id string, success bool) *Handshake {
return &Handshake{
ID: id,
Success: success,
Type: "handshake",
}
}
type Failure struct {
Reason string `json:"reason"`
Type string `json:"type"`
}
func NewFailure(reason string) *Failure {
return &Failure{
Reason: reason,
Type: "failure",
}
}

45
protocol/protocol_test.go Normal file
View File

@ -0,0 +1,45 @@
package protocol
import (
"encoding/json"
"testing"
)
type result struct {
b bool
msg string
}
type clientIDTest struct {
clientid ClientID
expected result
}
var clientIDTests = []clientIDTest{
{ClientID{Type: "robot"}, result{true, ""}},
{ClientID{Type: "spectator"}, result{true, ""}},
{ClientID{Type: "schmarglenoggler"}, result{false, "usergent must be 'robot' or 'spectator'"}},
}
func TestClientIDs(t *testing.T) {
for _, tt := range clientIDTests {
v, msg := tt.clientid.Valid()
actual := result{v, msg}
if actual.b != tt.expected.b || actual.msg != tt.expected.msg {
t.Errorf("%+v: expected %v, actual %v", tt.clientid, tt.expected, actual)
}
}
}
func TestClientIDParse(t *testing.T) {
var s ClientID
err := json.Unmarshal(
[]byte(`{
"type": "robot",
"name": "dummy",
"id": "24601",
"useragent": "gorobots.js"
}`), &s)
if err != nil {
t.Errorf("fail to parse: %v", err)
}
}