Skip to content

Commit

Permalink
Add (simple, one listener) long-polling support (api). Closes #307
Browse files Browse the repository at this point in the history
  • Loading branch information
42wim committed Dec 7, 2017
1 parent 5c919e6 commit d30ae19
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions bridge/api/api.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package api

import (
"encoding/json"
"github.com/42wim/matterbridge/bridge/config"
log "github.com/Sirupsen/logrus"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"github.com/zfjagann/golang-ring"
"net/http"
"sync"
"time"
)

type Api struct {
Expand Down Expand Up @@ -47,6 +49,7 @@ 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))
Expand Down Expand Up @@ -103,3 +106,25 @@ 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
}

0 comments on commit d30ae19

Please sign in to comment.