sse conforms to the gin.render.Render interface
This commit is contained in:
@@ -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
@@ -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")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user