O'Reilly logo

Go Web Development Cookbook by Arpit Aggarwal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required