forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
45 lines (37 loc) · 873 Bytes
/
socket.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
package actions
import (
"strings"
"time"
"github.com/gobuffalo/buffalo"
"github.com/pkg/errors"
)
type Message struct {
Original string `json:"original"`
Formatted string `json:"formatted"`
Received time.Time `json:"received"`
}
func SocketHandler(c buffalo.Context) error {
conn, err := c.Websocket()
if err != nil {
return errors.WithStack(err)
}
for {
// Read a message from the connection buffer.
_, m, err := conn.ReadMessage()
if err != nil {
return errors.WithStack(err)
}
// Convert the bytes we received to a string.
data := string(m)
// Create a message and store the data.
msg := Message{
Original: data,
Formatted: strings.ToUpper(data),
Received: time.Now(),
}
// Encode the message to JSON and send it back.
if err := conn.WriteJSON(msg); err != nil {
return errors.WithStack(err)
}
}
}