mirror of
https://github.com/PostHog/posthog.git
synced 2024-11-28 09:16:49 +01:00
61 lines
1.2 KiB
Go
61 lines
1.2 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
// Event structure is defined here: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format
|
||
|
type Event struct {
|
||
|
ID []byte
|
||
|
Data []byte
|
||
|
Event []byte
|
||
|
Retry []byte
|
||
|
Comment []byte
|
||
|
}
|
||
|
|
||
|
func (ev *Event) WriteTo(w http.ResponseWriter) error {
|
||
|
// Marshalling part is taken from: https://github.com/r3labs/sse/blob/c6d5381ee3ca63828b321c16baa008fd6c0b4564/http.go#L16
|
||
|
if len(ev.Data) == 0 && len(ev.Comment) == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
if len(ev.Data) > 0 {
|
||
|
if _, err := fmt.Fprintf(w, "id: %s\n", ev.ID); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
sd := bytes.Split(ev.Data, []byte("\n"))
|
||
|
for i := range sd {
|
||
|
if _, err := fmt.Fprintf(w, "data: %s\n", sd[i]); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if len(ev.Event) > 0 {
|
||
|
if _, err := fmt.Fprintf(w, "event: %s\n", ev.Event); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if len(ev.Retry) > 0 {
|
||
|
if _, err := fmt.Fprintf(w, "retry: %s\n", ev.Retry); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if len(ev.Comment) > 0 {
|
||
|
if _, err := fmt.Fprintf(w, ": %s\n", ev.Comment); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if _, err := fmt.Fprint(w, "\n"); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|