Fixes JSON rendering

This commit is contained in:
Manu Mtz-Almeida 2015-05-13 02:34:46 +02:00
parent 15b0c49da5
commit 57f6940dba
1 changed files with 8 additions and 5 deletions

View File

@ -24,18 +24,18 @@ func WriteSSEvent(w http.ResponseWriter, eventName string, data interface{}) err
} }
var stringData string var stringData string
switch typeOfData(data) { switch typeOfData(data) {
case reflect.Struct, reflect.Slice: case reflect.Struct, reflect.Slice, reflect.Map:
if jsonBytes, err := json.Marshal(data); err == nil { if jsonBytes, err := json.Marshal(data); err == nil {
stringData = string(jsonBytes) stringData = string(jsonBytes)
} else { } else {
return err return err
} }
case reflect.Ptr: case reflect.Ptr:
stringData = escape(fmt.Sprintf("%v", &data)) + "\n" stringData = escape(fmt.Sprintf("%v", &data))
default: default:
stringData = escape(fmt.Sprintf("%v", data)) + "\n" stringData = escape(fmt.Sprintf("%v", data))
} }
_, err := fmt.Fprintf(w, "event: %s\ndata: %s\n", escape(eventName), stringData) _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", escape(eventName), stringData)
return err return err
} }
@ -44,7 +44,10 @@ func typeOfData(data interface{}) reflect.Kind {
valueType := value.Kind() valueType := value.Kind()
if valueType == reflect.Ptr { if valueType == reflect.Ptr {
newValue := value.Elem().Kind() newValue := value.Elem().Kind()
if newValue == reflect.Struct || newValue == reflect.Slice { fmt.Println(newValue)
if newValue == reflect.Struct ||
newValue == reflect.Slice ||
newValue == reflect.Map {
return newValue return newValue
} else { } else {
return valueType return valueType