Thumbnail

rani/matterbridge.git

Clone URL: https://git.buni.party/rani/matterbridge.git

commit a367d290068ca0c4366f06118ffbc0f9ddb34d9b Author: Wim <wim@42.be> Date: Thu Dec 07 23:48:44 2017 +0000 Add (simple, one listener) long-polling support (api). Closes #307 diff --git a/bridge/api/api.go b/bridge/api/api.go index ab473af..b422c8d 100644 --- a/bridge/api/api.go +++ b/bridge/api/api.go @@ -16 +17 @@  package api    import ( + "encoding/json"   "github.com/42wim/matterbridge/bridge/config"   log "github.com/Sirupsen/logrus"   "github.com/labstack/echo" @@ -86 +97 @@ import (   "github.com/zfjagann/golang-ring"   "net/http"   "sync" + "time"  )    type Api struct { @@ -476 +497 @@ func New(cfg config.Protocol, account string, c chan config.Message) *Api {   }))   }   e.GET("/api/messages", b.handleMessages) + e.GET("/api/stream", b.handleStream)   e.POST("/api/message", b.handlePostMessage)   go func() {   flog.Fatal(e.Start(cfg.BindAddress)) @@ -1033 +10625 @@ func (b *Api) handleMessages(c echo.Context) error {   b.Messages = ring.Ring{}   return nil  } + +func (b *Api) handleStream(c echo.Context) error { + c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + c.Response().WriteHeader(http.StatusOK) + closeNotifier := c.Response().CloseNotify() + for { + select { + case <-closeNotifier: + return nil + default: + msg := b.Messages.Dequeue() + if msg != nil { + if err := json.NewEncoder(c.Response()).Encode(msg); err != nil { + return err + } + c.Response().Flush() + } + time.Sleep(200 * time.Millisecond) + } + } + return nil +}