Skip to content

Commit

Permalink
Use channels to avoid race conditions on websocket connection
Browse files Browse the repository at this point in the history
  • Loading branch information
pote committed Nov 16, 2018
1 parent ba92f74 commit 12ba9cb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
2 changes: 1 addition & 1 deletion VERSION.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package main

const VERSION = "0.3.0"
const VERSION = "0.3.1"
24 changes: 19 additions & 5 deletions philote.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,35 @@ import (
)

type Philote struct {
ID string
AccessKey *AccessKey
Hive *hive
ws *websocket.Conn
ID string
AccessKey *AccessKey
Hive *hive
ws *websocket.Conn
IncomingMessages chan *Message
}

func NewPhilote(ak *AccessKey, ws *websocket.Conn) (*Philote) {
p := &Philote{
ws: ws,
ID: uuid.NewV4().String(),
AccessKey: ak,
IncomingMessages: make(chan *Message),
}

go p.DistributeIncomingMessages()

return p
}

func (p *Philote) DistributeIncomingMessages() {
var message *Message

for {
message = <- p.IncomingMessages
p.ws.WriteJSON(message)
}
}

func (p *Philote) Listen() {
log.WithFields(log.Fields{"philote": p.ID}).Debug("Listening to Philote")
for {
Expand Down Expand Up @@ -69,9 +82,10 @@ func (p *Philote) publish(message *Message) {

for _, channel := range philote.AccessKey.Read {
if message.Channel == channel {
philote.ws.WriteJSON(message)
philote.IncomingMessages <- message
break
}
}

}
}

0 comments on commit 12ba9cb

Please sign in to comment.