WebSocket Chat Example
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
-
Clone the repository:
git clone https://github.com/gofiber/recipes.gitcd recipes/websocket-chat -
Install the dependencies:
go mod download -
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
- Open your browser and navigate to
http://localhost:8080. - Enter a message in the input field and click "Send".
- 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
clientstruct with a mutex and a closing flag to guard concurrent writes per connection. - Declares global channels (
register,broadcast,unregister) and a sharedclientsmap. runHub()runs in a goroutine and serialises map mutations: it adds connections onregister, fans out messages to all clients in parallel goroutines onbroadcast, and removes connections onunregister.main()parses the--addrflag, serveshome.htmlas a static file, upgrades/wsrequests 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.