bigbluebutton-Github/bbb-graphql-middleware/internal/common/SafeChannel.go
Gustavo Trott 095085310d
refactor: Graphql middleware enhancements (#19336)
* Convert all go chan to SafeChannel

* Remove unnecessary comments

* Refactor graphql message names

* Fix renamed function
2023-12-14 14:01:47 -03:00

48 lines
675 B
Go

package common
import (
"sync"
)
type SafeChannel struct {
ch chan interface{}
closed bool
mux sync.Mutex
}
func NewSafeChannel(size int) *SafeChannel {
return &SafeChannel{
ch: make(chan interface{}, size),
}
}
func (s *SafeChannel) Send(value interface{}) bool {
s.mux.Lock()
defer s.mux.Unlock()
if s.closed {
return false
}
s.ch <- value
return true
}
func (s *SafeChannel) Receive() (interface{}, bool) {
val, ok := <-s.ch
return val, ok
}
func (s *SafeChannel) ReceiveChannel() <-chan interface{} {
return s.ch
}
func (s *SafeChannel) Close() {
s.mux.Lock()
defer s.mux.Unlock()
if !s.closed {
close(s.ch)
s.closed = true
}
}