title | keywords | description | ||||
---|---|---|---|---|---|---|
WebSocket |
|
Real-time communication application using WebSockets. |
This example demonstrates a simple WebSocket application using Go Fiber.
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.
main.go
: The main application entry point.go.mod
: The Go module file.
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/websocket
-
Install the dependencies:
go mod download
-
Run the application:
go run main.go
The application should now be running on http://localhost:3000
.
- GET /ws: WebSocket endpoint for the application.
- 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.
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/v2"
"github.com/gofiber/contrib/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(403).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"))
}
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.