contrib icon indicating copy to clipboard operation
contrib copied to clipboard

🤗 [Question]: How to close websocket connection?

Open intezya opened this issue 1 year ago • 0 comments

Question Description

How to close websocket conn from other function? Why c.Close() dont work? image image

Code Snippet (optional)

package main

import (
	"github.com/gofiber/contrib/websocket"
	"github.com/gofiber/fiber/v2"
	"log"
)

type conns struct {
	connections map[string]*websocket.Conn
}

func someChecker(connections *conns) {
	log.Println("starting some checker")
	for {
		for key, value := range connections.connections {
			if key != "some_check" {
				err := value.Close()
				if err != nil {
					log.Println("error closing connection", err)
				} else {
					log.Println("connection closed") // Prints closed but not closed
				}
				delete(connections.connections, key)
			}
		}
	}
}

func main() {
	connections := conns{connections: make(map[string]*websocket.Conn)}
	app := fiber.New()
	app.Get(
		"/ws", websocket.New(
			func(c *websocket.Conn) {
				connections.connections[c.RemoteAddr().String()] = c
				for {
					_, _, err := c.ReadMessage()
					if err != nil {
						break
					}
				}
			},
		),
	)

	go someChecker(&connections)
	log.Fatal(app.Listen(":3000"))
}

Checklist:

  • [X] I agree to follow Fiber's Code of Conduct.
  • [X] I have checked for existing issues that describe my questions prior to opening this one.
  • [X] I understand that improperly formatted questions may be closed without explanation.

intezya avatar Dec 16 '24 15:12 intezya