Skip to content

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

@intezya

Description

@intezya

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    🤔 QuestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions