2
0

sse conforms to the gin.render.Render interface

This commit is contained in:
Manu Mtz-Almeida
2015-05-18 15:44:06 +02:00
parent c60c0e49b3
commit 320b4a6cca
2 changed files with 26 additions and 0 deletions
+11
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strings"
)
@@ -21,6 +22,16 @@ type Event struct {
Data interface{}
}
func (r Event) Write(w http.ResponseWriter) error {
header := w.Header()
header.Set("Content-Type", ContentType)
if _, exist := header["Cache-Control"]; !exist {
header.Set("Cache-Control", "no-cache")
}
return Encode(w, r)
}
func Encode(w io.Writer, event Event) error {
writeId(w, event.Id)
writeEvent(w, event.Event)
+15
View File
@@ -2,6 +2,7 @@ package sse
import (
"bytes"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
@@ -144,3 +145,17 @@ func TestEncodeStream(t *testing.T) {
})
assert.Equal(t, w.String(), "event: float\ndata: 1.5\n\nid: 123\ndata: {\"bar\":\"foo\",\"foo\":\"bar\"}\n\nid: 124\nevent: chat\ndata: hi! dude\n\n")
}
func TestRenderSSE(t *testing.T) {
w := httptest.NewRecorder()
err := (Event{
Event: "msg",
Data: "hi! how are you?",
}).Write(w)
assert.NoError(t, err)
assert.Equal(t, w.Body.String(), "event: msg\ndata: hi! how are you?\n\n")
assert.Equal(t, w.Header().Get("Content-Type"), "text/event-stream")
assert.Equal(t, w.Header().Get("Cache-Control"), "no-cache")
}