76 lines
1.3 KiB
Go
76 lines
1.3 KiB
Go
package resp
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
)
|
|
|
|
type SSEManager struct {
|
|
c fiber.Ctx
|
|
event string
|
|
ch chan string
|
|
id int64
|
|
}
|
|
|
|
func (m *SSEManager) Send(msg string) {
|
|
m.ch <- msg
|
|
}
|
|
|
|
func (m *SSEManager) JSON(data any) {
|
|
bs, err := json.Marshal(data)
|
|
if err != nil {
|
|
m.ch <- err.Error()
|
|
return
|
|
}
|
|
|
|
m.ch <- string(bs)
|
|
}
|
|
|
|
func (m *SSEManager) Writer() func(w *bufio.Writer) {
|
|
return func(w *bufio.Writer) {
|
|
for msg := range m.ch {
|
|
fmt.Fprintf(w, "event: %s\nid: %d\ntimestamp: %d\ndata: %s\n\n", m.event, m.id, time.Now().UnixMilli(), msg)
|
|
w.Flush()
|
|
m.id++
|
|
}
|
|
w.Flush()
|
|
}
|
|
}
|
|
|
|
func (m *SSEManager) Close() {
|
|
close(m.ch)
|
|
}
|
|
|
|
// SSE create a new SSEManager
|
|
// example:
|
|
//
|
|
// func someHandler(c fiber.Ctx) error {
|
|
// m := resp.SSE(c, "test")
|
|
// go func() {
|
|
// defer m.Close()
|
|
// for i := range 10 {
|
|
// m.Send("test" + strconv.Itoa(i))
|
|
// time.Sleep(1 * time.Second)
|
|
// }
|
|
// }()
|
|
//
|
|
// return c.SendStreamWriter(m.Writer())
|
|
// }
|
|
func SSE(c fiber.Ctx, event string) *SSEManager {
|
|
c.Set("Content-Type", "text/event-stream")
|
|
c.Set("Cache-Control", "no-cache")
|
|
c.Set("Connection", "keep-alive")
|
|
c.Set("Transfer-Encoding", "chunked")
|
|
|
|
return &SSEManager{
|
|
c: c,
|
|
event: event,
|
|
id: 0,
|
|
ch: make(chan string, 1),
|
|
}
|
|
}
|