recipes/websocket
WebSocket
Real-time communication application using WebSockets.
WebSocket Example
This example demonstrates a simple WebSocket application using Go Fiber.
Description
This project provides a basic setup for a WebSocket server using Go Fiber. It includes the necessary configuration and code to run a real-time WebSocket server.
Requirements
Project Structure
main.go: The main application entry point.go.mod: The Go module file.
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/websocketInstall the dependencies:
go mod downloadRun the application:
go run main.go
The application should now be running on http://localhost:3000.
WebSocket Endpoint
- GET /ws: WebSocket endpoint for the application.
Example Usage
- Connect to the WebSocket server at
ws://localhost:3000/ws. - Send a message to the server.
- The server will echo the message back to the client.
Code Overview
main.go
The main Go file sets up the Fiber application, handles WebSocket connections, and manages the WebSocket communication.
package main
import (
"fmt"
"log"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/contrib/v3/websocket"
)
func main() {
app := fiber.New()
// Optional middleware
app.Use("/ws", func(c fiber.Ctx) error {
if c.Get("host") == "localhost:3000" {
c.Locals("Host", "Localhost:3000")
return c.Next()
}
return c.Status(fiber.StatusForbidden).SendString("Request origin not allowed")
})
// Upgraded websocket request
app.Get("/ws", websocket.New(func(c *websocket.Conn) {
fmt.Println(c.Locals("Host")) // "Localhost:3000"
for {
mt, msg, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", msg)
err = c.WriteMessage(mt, msg)
if err != nil {
log.Println("write:", err)
break
}
}
}))
// ws://localhost:3000/ws
log.Fatal(app.Listen(":3000"))
}Going further
This recipe echoes each message back to the sender. Two common next steps:
- Broadcasting to many clients, such as a chat room. Keep a registry of connections and write to all of them, guarding each connection against concurrent writes and removing clients when they drop. The WebSocket Shared State recipe shows this pattern together with thread-safe shared state.
- The Socket.IO protocol. If your clients use a Socket.IO library rather than the plain WebSocket API, see the Socketio recipe. It uses the
socketiopackage from Fiber contrib, which builds on thewebsocketpackage used here.
Conclusion
This example provides a basic setup for a WebSocket server using Go Fiber. It can be extended and customized further to fit the needs of more complex applications.