mirror of https://github.com/gin-gonic/gin.git
Using github.com/manucorporat/sse
This commit is contained in:
parent
7149009a84
commit
b0af2b4c11
|
@ -1,10 +1,9 @@
|
||||||
package render
|
package render
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"reflect"
|
|
||||||
|
"github.com/manucorporat/sse"
|
||||||
)
|
)
|
||||||
|
|
||||||
type sseRender struct{}
|
type sseRender struct{}
|
||||||
|
@ -20,42 +19,10 @@ func (_ sseRender) Render(w http.ResponseWriter, code int, data ...interface{})
|
||||||
func WriteSSEvent(w http.ResponseWriter, eventName string, data interface{}) error {
|
func WriteSSEvent(w http.ResponseWriter, eventName string, data interface{}) error {
|
||||||
header := w.Header()
|
header := w.Header()
|
||||||
if len(header.Get("Content-Type")) == 0 {
|
if len(header.Get("Content-Type")) == 0 {
|
||||||
w.Header().Set("Content-Type", "text/event-stream")
|
header.Set("Content-Type", "text/event-stream")
|
||||||
}
|
}
|
||||||
var stringData string
|
return sse.Encode(w, sse.Event{
|
||||||
switch typeOfData(data) {
|
Event: eventName,
|
||||||
case reflect.Struct, reflect.Slice, reflect.Map:
|
Data: data,
|
||||||
if jsonBytes, err := json.Marshal(data); err == nil {
|
})
|
||||||
stringData = string(jsonBytes)
|
|
||||||
} else {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
case reflect.Ptr:
|
|
||||||
stringData = escape(fmt.Sprintf("%v", &data))
|
|
||||||
default:
|
|
||||||
stringData = escape(fmt.Sprintf("%v", data))
|
|
||||||
}
|
|
||||||
_, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", escape(eventName), stringData)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func typeOfData(data interface{}) reflect.Kind {
|
|
||||||
value := reflect.ValueOf(data)
|
|
||||||
valueType := value.Kind()
|
|
||||||
if valueType == reflect.Ptr {
|
|
||||||
newValue := value.Elem().Kind()
|
|
||||||
fmt.Println(newValue)
|
|
||||||
if newValue == reflect.Struct ||
|
|
||||||
newValue == reflect.Slice ||
|
|
||||||
newValue == reflect.Map {
|
|
||||||
return newValue
|
|
||||||
} else {
|
|
||||||
return valueType
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return valueType
|
|
||||||
}
|
|
||||||
|
|
||||||
func escape(str string) string {
|
|
||||||
return str
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue