forked from Ayo-Awe/go-sse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
43 lines (34 loc) · 872 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main
import (
"fmt"
"log/slog"
"net/http"
"time"
"github.com/awe-ayo/go-sse/sse"
)
func main() {
sse := sse.New()
mux := http.NewServeMux()
mux.Handle("/sse", sse)
mux.HandleFunc("POST /ping/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
msg := fmt.Sprintf("Hello %s", id)
if err := sse.Publish(id, msg); err != nil {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "failed to publish event")
return
}
w.WriteHeader(http.StatusOK)
})
go func() {
ticker := time.NewTicker(1 * time.Second)
for currentTime := range ticker.C {
sse.Broadcast(currentTime.Format(time.DateTime))
}
}()
port := 3020
slog.Info("starting server", "port", port)
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), mux); err != nil {
slog.Error("failed to start server", "err", err, "port", port)
}
}