Golang Gorilla Websocket Example: A Comprehensive Guide

Golang is a programming language that has gained popularity over the years due to its efficiency and simplicity. Gorilla Websocket is a library for building Websocket servers and clients in Golang. This library provides a clean and easy-to-use API for developers to build Websocket applications. In this article, we will be discussing Golang Gorilla Websocket Example in detail.

What is Gorilla Websocket?

Gorilla Websocket is a library for building Websocket servers and clients in Golang. It provides a clean and easy-to-use API for developers to build Websocket applications. Websockets enable real-time communication between clients and servers. With Websockets, clients and servers can send messages to each other without having to establish a new HTTP connection for each message.

Gorilla Websocket is built on top of the standard net/http package in Golang. It supports the latest Websocket protocol and provides features like message fragmentation, ping-pong messages, and close messages. Gorilla Websocket is widely used in building real-time applications like chat applications, real-time gaming, and collaborative applications.

Getting Started with Gorilla Websocket

Before we dive into building a Golang Gorilla Websocket Example, we need to have some knowledge of Golang and Websockets. If you are new to Golang or Websockets, we recommend going through the official documentation of Golang and Websockets.

Once you are familiar with Golang and Websockets, we can move on to installing Gorilla Websocket. To install Gorilla Websocket, run the following command:

go get github.com/gorilla/websocket

This command will install Gorilla Websocket and its dependencies.

Building a Golang Gorilla Websocket Example

Now that we have installed Gorilla Websocket, we can start building our Golang Gorilla Websocket Example. In this example, we will be building a simple chat application that allows users to send and receive messages in real-time.

Step 1: Setting up the Server

The first step in building our Golang Gorilla Websocket Example is setting up the server. To set up the server, we need to create a new instance of the http.Server struct and configure it to handle Websocket connections. Here is the code for setting up the server:

import ("github.com/gorilla/websocket""net/http")

var upgrader = websocket.Upgrader{ReadBufferSize:1024,WriteBufferSize: 1024,}

func handleConnections(w http.ResponseWriter, r *http.Request) {// Upgrade initial GET request to a websocketws, err := upgrader.Upgrade(w, r, nil)if err != nil {log.Fatal(err)}defer ws.Close()

// Register our new clientclients[ws] = true

for {// Read in a new message_, msg, err := ws.ReadMessage()if err != nil {log.Printf("error: %v", err)delete(clients, ws)break}

// Send the newly received message to the broadcast channelbroadcast <- msg}}

func main() {// Configure the websocket routehttp.HandleFunc("/ws", handleConnections)

// Start the server on localhost port 8000 and log any errorslog.Println("http server started on :8000")err := http.ListenAndServe(":8000", nil)if err != nil {log.Fatal("error starting http server:", err)}}

In the code above, we imported the Gorilla Websocket library and created a new instance of the websocket.Upgrader struct. The Upgrader struct is used to upgrade the initial HTTP request to a Websocket connection. We set the ReadBufferSize and WriteBufferSize to 1024 bytes.

We then defined the handleConnections function, which is responsible for handling Websocket connections. In this function, we upgraded the initial HTTP request to a Websocket connection using the Upgrader struct. We then registered the new client and added it to the clients map. The clients map is used to keep track of all connected clients.

We then read in a new message from the client and sent it to the broadcast channel. The broadcast channel is used to send messages to all connected clients.

Finally, we defined the main function, which configures the Websocket route and starts the server.

Step 2: Setting up the Client

Now that we have set up the server, we can move on to setting up the client. To set up the client, we need to create a new WebSocket object and configure it to connect to the server. Here is the code for setting up the client:

var socket = new WebSocket("ws://" + window.location.hostname + ":8000/ws");

socket.onmessage = function(event) {var message = event.data;console.log(message);};

socket.onclose = function(event) {console.log("WebSocket is closed now.");};

function sendMessage() {var message = document.getElementById("message").value;socket.send(message);}

In the code above, we created a new WebSocket object and set its URL to “ws://” + window.location.hostname + “:8000/ws”. This URL specifies the URL of the Websocket server that we set up in Step 1.

We then defined the onmessage function, which is called whenever a new message is received from the server. In this function, we simply log the message to the console.

We also defined the onclose function, which is called whenever the Websocket connection is closed. In this function, we log a message to the console.

Finally, we defined the sendMessage function, which is called whenever the user sends a message. In this function, we get the value of the message input field and send it to the server using the socket.send() method.

Step 3: Broadcasting Messages

Now that we have set up the server and client, we need to implement the logic for broadcasting messages to all connected clients. To do this, we will use a channel to send messages from the server to all connected clients. Here is the code for broadcasting messages:

var clients = make(map[*websocket.Conn]bool) // connected clientsvar broadcast = make(chan []byte)// broadcast channel

func broadcastMessages() {for {// Grab the next message from the broadcast channelmsg := <-broadcast

// Send the message to all connected clientsfor client := range clients {err := client.WriteMessage(websocket.TextMessage, msg)if err != nil {log.Printf("error: %v", err)client.Close()delete(clients, client)}}}}

func main() {// Configure the websocket routehttp.HandleFunc("/ws", handleConnections)

// Start the server on localhost port 8000 and log any errorslog.Println("http server started on :8000")

go broadcastMessages()

err := http.ListenAndServe(":8000", nil)if err != nil {log.Fatal("error starting http server:", err)}}

In the code above, we defined the clients map and the broadcast channel. The clients map is used to keep track of all connected clients, and the broadcast channel is used to send messages to all connected clients.

We then defined the broadcastMessages function, which is responsible for broadcasting messages to all connected clients. In this function, we loop through all connected clients and send the message to each client using the WriteMessage method.

We also added a call to the broadcastMessages function in the main function to start broadcasting messages.

Conclusion

In this article, we discussed Golang Gorilla Websocket Example in detail. We learned what Gorilla Websocket is and how it can be used to build real-time applications. We also went through the steps involved in building a Golang Gorilla Websocket Example. We went over setting up the server, setting up the client, and broadcasting messages to all connected clients. We hope this article has been helpful in getting you started with building real-time applications using Golang and Gorilla Websocket.

FAQs

  1. What is Golang?

    Golang is a programming language developed by Google. It is known for its efficiency and simplicity.

  2. What is Gorilla Websocket?

    Gorilla Websocket is a library for building Websocket servers and clients in Golang.

  3. What are Websockets?

    Websockets enable real-time communication between clients and servers. With Websockets, clients and servers can send messages to each other without having to establish a new HTTP connection for each message.

  4. What can I build with Gorilla Websocket?

    Gorilla Websocket can be used to build real-time applications like chat applications, real-time gaming, and collaborative applications.

  5. How do I install Gorilla Websocket?

    To install Gorilla Websocket, run the following command: go get github.com/gorilla/websocket