Education logo

Golang and WebSockets

Building a real-time application with Golang and WebSockets.

By robertsamuelPublished about a year ago 3 min read
Like

Sure, I can help you with that! Here's a blog post on how to build a real-time application with Golang and WebSockets:

Real-time applications are becoming more and more popular as users expect to see updates to their data in real-time. Golang, with its high concurrency and scalability, is a great language for building real-time applications. WebSockets, on the other hand, provide a real-time, bidirectional communication channel between the client and server. In this blog post, we'll explore how to use Golang and WebSockets to build a real-time application.

What are WebSockets?

WebSockets are a protocol that provides a full-duplex, real-time communication channel between the client and server. It allows the server to send data to the client whenever it's available, without the client having to make a request. The client can also send data to the server, making it a bidirectional communication channel. This makes WebSockets an ideal choice for building real-time applications such as chat applications, online gaming, and more.

Setting up the project

Before we start building our real-time application, we need to set up our project. We'll use the Gorilla WebSocket library, which provides a WebSocket implementation for Golang. To install the library, run the following command:

go get github.com/gorilla/websocket

Next, create a new directory for our project and navigate into it:

mkdir realtime-app && cd realtime-app

Create a new file called main.go and open it in your text editor.

Creating a WebSocket server

Now that we have our project set up, we can start building our WebSocket server. The first thing we need to do is create a WebSocket endpoint that the client can connect to. We'll use the Gorilla WebSocket library to do this.

package main

import (

"log"

"net/http"

"github.com/gorilla/websocket"

)

var upgrader = websocket.Upgrader{

ReadBufferSize: 1024,

WriteBufferSize: 1024,

}

func main() {

http.HandleFunc("/ws", handleWebSocket)

err := http.ListenAndServe(":8080", nil)

if err != nil {

log.Fatal("Error starting server: ", err)

}

}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {

conn, err := upgrader.Upgrade(w, r, nil)

if err != nil {

log.Println("Error upgrading to WebSocket: ", err)

return

}

defer conn.Close()

// Do something with the WebSocket connection here

}

In the above code, we define an HTTP handler function called handleWebSocket that is called when the client connects to the /ws endpoint. The upgrader variable is used to upgrade the HTTP connection to a WebSocket connection. The ReadBufferSize and WriteBufferSize are set to 1024 bytes each.

In the handleWebSocket function, we upgrade the connection to a WebSocket connection using the upgrader. We then defer closing the connection. Finally, we can do something with the WebSocket connection here.

Sending and receiving messages

Now that we have our WebSocket server set up, let's add some functionality to send and receive messages between the client and server. We'll define a struct to represent a message and a map to store all the WebSocket connections.

type Message struct {

Username string `json:"username"`

Message string `json:"message"`

}

var connections = make(map[*websocket.Conn]bool)

type Message struct {

Username string `json:"username"`

Message string `json:"message"`

}

var connections = make(map[*websocket.Conn]bool)

func handleWebSocket(w http.ResponseWriter, r *http.Request) {

conn, err := upgrader.Upgrade

if err != nil {

log.Println("Error upgrading to WebSocket: ", err)

return

}

defer conn.Close()

// Add the connection to the connections map

connections[conn] = true

for {

// Read message from the WebSocket connection

message := Message{}

err := conn.ReadJSON(&message)

if err != nil {

log.Println("Error reading message: ", err)

delete(connections, conn)

return

}

// Broadcast the message to all WebSocket connections

for conn := range connections {

err := conn.WriteJSON(message)

if err != nil {

log.Println("Error broadcasting message: ", err)

conn.Close()

delete(connections, conn)

}

}

}

const socket = new WebSocket('ws://localhost:8080/ws')

socket.addEventListener('open', event => {

console.log('Connected to WebSocket server')

})

socket.addEventListener('message', event => {

const message = JSON.parse(event.data)

console.log(Received message from ${message.username}: ${message.message})

})

const sendMessage = () => {

const username = document.getElementById('username').value

const message = document.getElementById('message').value

const data = JSON.stringify({ username, message })

socket.send(data)

}

Visit Golang Development Company..

courses
Like

About the Creator

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2024 Creatd, Inc. All Rights Reserved.