-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
73 lines (57 loc) · 1.2 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// The API handlers for manipulating board state.
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
type coord struct {
Row int `form:"row" json:"row"`
Col int `form:"col" json:"col"`
}
type pixel struct {
coord
Color int `form:"color" json:"color"`
}
func getPixel(c *gin.Context) {
var co coord
if err := c.Bind(&co); err != nil {
return
}
val, err := board.getPixel(co.Row, co.Col)
if err != nil {
log.Println("getPixel:", err)
c.String(http.StatusServiceUnavailable, "db error")
return
}
c.JSON(http.StatusOK, val)
}
func setPixel(c *gin.Context) {
var p pixel
if err := c.Bind(&p); err != nil {
return
}
err := board.setPixel(p.Row, p.Col, p.Color)
if err != nil {
log.Println("setPixel:", err)
c.String(http.StatusServiceUnavailable, "db error")
return
}
c.JSON(http.StatusOK, p.Color)
// Send the update to the websocket server.
data, err := json.Marshal(p)
if err != nil {
log.Println(err)
}
wss.broadcast <- data
}
func getBoard(c *gin.Context) {
val, err := board.getBoard()
if err != nil {
log.Println("getBoard:", err)
c.String(http.StatusServiceUnavailable, "db error")
return
}
c.String(http.StatusOK, val)
}