package rest_websocket import ( "context" "log" ) func NewApplication(ctx context.Context) *Application { app := &Application{ ctx: ctx, chConnect: make(chan *SocketServer), chDisconnect: make(chan *SocketServer), } go app.work() return app } type Application struct { sockets []*SocketServer ctx context.Context chConnect chan *SocketServer chDisconnect chan *SocketServer } func (s *Application) Connect() chan<- *SocketServer { return s.chConnect } func (s *Application) Disconnect() chan<- *SocketServer { return s.chDisconnect } func (s *Application) work() { for { select { case <-s.ctx.Done(): return case socket, ok := <-s.chConnect: if !ok { return } log.Println("CH-CONNECT") s.addSocket(socket) case socket := <-s.chDisconnect: log.Println("CH-DISCONNECT") for i, sock := range s.sockets { if sock == socket { s.sockets[i] = nil break } } } } } func (s *Application) searchFree() (int, bool) { for i, sock := range s.sockets { if sock == nil { return i, true } } return -1, false } func (s *Application) addSocket(socket *SocketServer) { log.Println("ADD_SOCKET", socket) // ищем свободный слот index, free := s.searchFree() if !free { sockets := make([]*SocketServer, len(s.sockets)+50) copy(sockets, s.sockets) sockets[len(s.sockets)] = socket } else { s.sockets[index] = socket } }