github.com/rotblauer/buffalo@v0.7.1-0.20170112214545-7aa55ef80dd3/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  type Message struct {
    12  	Original  string    `json:"original"`
    13  	Formatted string    `json:"formatted"`
    14  	Received  time.Time `json:"received"`
    15  }
    16  
    17  func SocketHandler(c buffalo.Context) error {
    18  	conn, err := c.Websocket()
    19  	if err != nil {
    20  		return errors.WithStack(err)
    21  	}
    22  	for {
    23  
    24  		// Read a message from the connection buffer.
    25  		_, m, err := conn.ReadMessage()
    26  		if err != nil {
    27  			return errors.WithStack(err)
    28  		}
    29  
    30  		// Convert the bytes we received to a string.
    31  		data := string(m)
    32  
    33  		// Create a message and store the data.
    34  		msg := Message{
    35  			Original:  data,
    36  			Formatted: strings.ToUpper(data),
    37  			Received:  time.Now(),
    38  		}
    39  
    40  		// Encode the message to JSON and send it back.
    41  		if err := conn.WriteJSON(msg); err != nil {
    42  			return errors.WithStack(err)
    43  		}
    44  	}
    45  }