Skip to main content

WebSocket Chat Example

Github StackBlitz

This example demonstrates a simple chat application using Go Fiber and WebSockets.

Description​

This project provides a basic setup for a WebSocket-based chat application using Go Fiber. It includes the necessary configuration and code to run a real-time chat server.

Requirements​

Project Structure​

  • main.go: The main application entry point.
  • home.html: The HTML file for the chat client.
  • go.mod: The Go module file.

Setup​

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/websocket-chat
  2. Install the dependencies:

    go mod download
  3. Run the application:

    go run main.go

The application should now be running on http://localhost:8080.

WebSocket Endpoints​

  • GET /ws: WebSocket endpoint for the chat application.

Example Usage​

  1. Open your browser and navigate to http://localhost:8080.
  2. Enter a message in the input field and click "Send".
  3. The message should appear in the chat log.

Code Overview​

main.go​

The main Go file sets up the Fiber application, handles WebSocket connections, and manages the chat hub.

  • Defines a client struct with a mutex and a closing flag to guard concurrent writes per connection.
  • Declares global channels (register, broadcast, unregister) and a shared clients map.
  • runHub() runs in a goroutine and serialises map mutations: it adds connections on register, fans out messages to all clients in parallel goroutines on broadcast, and removes connections on unregister.
  • main() parses the --addr flag, serves home.html as a static file, upgrades /ws requests to WebSocket, and starts the hub before listening.

home.html​

The HTML file provides a simple user interface for the chat application, including a message log and input field.

Conclusion​

This example provides a basic setup for a WebSocket-based chat application using Go Fiber. It can be extended and customized further to fit the needs of more complex applications.

References​