Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🤗 [Question]: How to close websocket connection? #1213

Open
3 tasks done
intezya opened this issue Dec 16, 2024 · 0 comments
Open
3 tasks done

🤗 [Question]: How to close websocket connection? #1213

intezya opened this issue Dec 16, 2024 · 0 comments
Labels
🤔 Question Further information is requested

Comments

@intezya
Copy link

intezya commented Dec 16, 2024

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:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my questions prior to opening this one.
  • I understand that improperly formatted questions may be closed without explanation.
@intezya intezya added the 🤔 Question Further information is requested label Dec 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🤔 Question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant