Using one connection for multiple authenticated clients

This commit is contained in:
2023-09-19 20:40:52 -05:00
parent 832e02f42f
commit c4ebd5d6ff
3 changed files with 30 additions and 25 deletions

View File

@ -11,35 +11,33 @@ var ErrInvalidChannelName = errors.New("invalid channel channel")
type Unsubscriber func(subscription *Subscription) error
type Subscription struct {
channel string
unsub Unsubscriber
msgCh chan *message.Message
channel string
authToken string
unsub Unsubscriber
msgCh chan *message.Message
}
// todo error
func NewSubscription(chanel string, unsub Unsubscriber, msgCh chan *message.Message) (*Subscription, error) {
func NewSubscription(chanel string, unsub Unsubscriber, authToken string, msgCh chan *message.Message) (*Subscription, error) {
if !IsValidSubscriptionName(chanel) {
return nil, ErrInvalidChannelName
}
return &Subscription{
channel: chanel,
unsub: unsub,
msgCh: msgCh,
channel: chanel,
authToken: authToken,
unsub: unsub,
msgCh: msgCh,
}, nil
}
func (s *Subscription) OnMessage(onMessage func(channel string, msg message.Data)) error {
var inMsg *message.Message
go func() error {
for inMsg = range s.msgCh {
if inMsg.GetError() != nil {
return inMsg.GetError()
}
onMessage(inMsg.Channel, inMsg.Data)
for inMsg = range s.msgCh {
if inMsg.GetError() != nil {
return inMsg.GetError()
}
return nil
}()
onMessage(inMsg.Channel, inMsg.Data)
}
return nil
}
@ -56,6 +54,10 @@ func (s *Subscription) Unsubscribe() error {
return s.unsub(s)
}
func (s *Subscription) AuthToken() string {
return s.authToken
}
// validChannelName channel specifies is the channel is in the format /foo/432/bar
var validChannelName = regexp.MustCompile(`^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$`)