github.com/lenfree/buffalo@v0.7.3-0.20170207163156-891616ea4064/examples/websockets/actions/socket.go (about) 1 package actions 2 3 import ( 4 "strings" 5 "time" 6 7 "github.com/gobuffalo/buffalo" 8 "github.com/pkg/errors" 9 ) 10 11 // Message stores incoming data from websocket connection buffer 12 type Message struct { 13 Original string `json:"original"` 14 Formatted string `json:"formatted"` 15 Received time.Time `json:"received"` 16 } 17 18 // SocketHandler reads messages from the websocket connection buffer and returns 19 // the original message, formatted (uppercase) message, and received time in JSON 20 func SocketHandler(c buffalo.Context) error { 21 conn, err := c.Websocket() 22 if err != nil { 23 return errors.WithStack(err) 24 } 25 for { 26 // Read a message from the connection buffer. 27 _, m, err := conn.ReadMessage() 28 if err != nil { 29 return errors.WithStack(err) 30 } 31 32 // Convert the bytes we received to a string. 33 data := string(m) 34 35 // Create a message and store the data. 36 msg := Message{ 37 Original: data, 38 Formatted: strings.ToUpper(data), 39 Received: time.Now(), 40 } 41 42 // Encode the message to JSON and send it back. 43 if err := conn.WriteJSON(msg); err != nil { 44 return errors.WithStack(err) 45 } 46 } 47 }