How to do it...

  1. Install the github.com/gorilla/websocket package using the go get command, as follows:
$ go get github.com/gorilla/websocket
  1. 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 ...

Get Go Web Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.