diff --git a/README.md b/README.md index 67e3ab5..1a71400 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,49 @@ your way so you can write real-time apps. Features include: go get gopkg.in/olahol/melody.v1 ``` + +## [Example: sub/pub](https://) + +```go +package main + +import ( + "log" + "melody" + + "github.com/gin-gonic/gin" +) + +func main() { + m := melody.New() + router := gin.Default() + router.GET("/chat", func(context *gin.Context) { + if err := m.HandleRequest(context.Writer, context.Request); err != nil { + log.Println(err) + } + }) + + m.HandleConnect(func(session *melody.Session) { + ch := session.Request.URL.Query().Get("channel") + if err := session.Subscribe(ch); err != nil { + log.Println(err) + } + }) + + m.HandleMessage(func(session *melody.Session, msg []byte) { + if err := session.Publish(msg); err != nil { + log.Println(err) + } + }) + + m.HandleSentMessage(func(session *melody.Session, bytes []byte) { + log.Printf("%+v", session.Channel().Online()) + log.Printf("%+v", string(bytes)) + }) + router.Run(":8080") +} +``` + ## [Example: chat](https://github.com/olahol/melody/tree/master/examples/chat) [![Chat](https://cdn.rawgit.com/olahol/melody/master/examples/chat/demo.gif "Demo")](https://github.com/olahol/melody/tree/master/examples/chat) diff --git a/examples/broadcast/broadcast b/examples/broadcast/broadcast deleted file mode 100644 index e874895..0000000 Binary files a/examples/broadcast/broadcast and /dev/null differ diff --git a/examples/broadcast/main.go b/examples/broadcast/main.go index 19956a0..eb592de 100644 --- a/examples/broadcast/main.go +++ b/examples/broadcast/main.go @@ -21,12 +21,21 @@ func main() { if err := session.Subscribe(ch); err != nil { log.Println(err) } + session.Set("channel", ch) }) m.HandleMessage(func(session *melody.Session, msg []byte) { - if err := session.Publish(msg); err != nil { - log.Println(err) + channel, ok1 := session.Get("channel") + if ok1 { + _ = m.BroadcastFilter(msg, func(s *melody.Session) bool { + ch, ok2 := s.Get("channel") + if ok2 && ch.(string) == channel.(string) { + return true + } + return false + }) } + }) m.HandleSentMessage(func(session *melody.Session, bytes []byte) { diff --git a/examples/channel/main.go b/examples/sub-pub/main.go similarity index 72% rename from examples/channel/main.go rename to examples/sub-pub/main.go index eb592de..19956a0 100644 --- a/examples/channel/main.go +++ b/examples/sub-pub/main.go @@ -21,21 +21,12 @@ func main() { if err := session.Subscribe(ch); err != nil { log.Println(err) } - session.Set("channel", ch) }) m.HandleMessage(func(session *melody.Session, msg []byte) { - channel, ok1 := session.Get("channel") - if ok1 { - _ = m.BroadcastFilter(msg, func(s *melody.Session) bool { - ch, ok2 := s.Get("channel") - if ok2 && ch.(string) == channel.(string) { - return true - } - return false - }) + if err := session.Publish(msg); err != nil { + log.Println(err) } - }) m.HandleSentMessage(func(session *melody.Session, bytes []byte) {