2015-05-12 16:33:41 +00:00
|
|
|
package render
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2015-05-13 18:27:45 +00:00
|
|
|
|
|
|
|
"github.com/manucorporat/sse"
|
2015-05-12 16:33:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type sseRender struct{}
|
|
|
|
|
|
|
|
var SSEvent Render = sseRender{}
|
|
|
|
|
|
|
|
func (_ sseRender) Render(w http.ResponseWriter, code int, data ...interface{}) error {
|
|
|
|
eventName := data[0].(string)
|
|
|
|
obj := data[1]
|
|
|
|
return WriteSSEvent(w, eventName, obj)
|
|
|
|
}
|
|
|
|
|
|
|
|
func WriteSSEvent(w http.ResponseWriter, eventName string, data interface{}) error {
|
|
|
|
header := w.Header()
|
|
|
|
if len(header.Get("Content-Type")) == 0 {
|
2015-05-13 21:24:56 +00:00
|
|
|
header.Set("Content-Type", sse.ContentType)
|
2015-05-12 16:33:41 +00:00
|
|
|
}
|
2015-05-14 00:08:47 +00:00
|
|
|
if len(header.Get("Cache-Control")) == 0 {
|
|
|
|
header.Set("Cache-Control", "no-cache")
|
|
|
|
}
|
2015-05-13 18:27:45 +00:00
|
|
|
return sse.Encode(w, sse.Event{
|
|
|
|
Event: eventName,
|
|
|
|
Data: data,
|
|
|
|
})
|
2015-05-12 16:33:41 +00:00
|
|
|
}
|