Creating your first WebSocket server
In this recipe, we will learn how to write a WebSocket server, which is a TCP application listening on port 8080
that allows connected clients to send messages to each other.
How to do it…
- Install the
github.com/gorilla/websocket
package using thego get
command, as follows:
$ go get github.com/gorilla/websocket
- Create
websocket-server.go
where we will upgrade an HTTP request to WebSocket, read the JSON message from the client, and broadcast it to all of the connected clients, as follows:
package main import ( "log" "net/http" "github.com/gorilla/websocket" ) var clients = make(map[*websocket.Conn]bool) var broadcast = make(chan Message) var upgrader = websocket.Upgrader{} type Message struct { Message string `json:"message"` } func HandleClients(w http.ResponseWriter, r *http.Request) { go broadcastMessagesToClients() websocket, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Fatal("error upgrading GET request to a websocket...