-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
41 lines (34 loc) · 1 KB
/
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
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
eventChan := make(chan string) // Channel to send events to clients
http.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*")
for {
eventData := <-eventChan
fmt.Fprintf(w, "data: %s\n\n", eventData)
w.(http.Flusher).Flush()
}
})
http.HandleFunc("/send-event", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(10 * time.Second)
eventData := fmt.Sprintf("Button clicked at %s", time.Now().Format("2006-01-02 15:04:05"))
eventChan <- eventData
w.WriteHeader(http.StatusOK)
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Failed to start the server:", err)
return
}
}