54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
var eventChan = make(chan string)
|
|
|
|
func SSEHandler(w http.ResponseWriter, r *http.Request) {
|
|
log.Printf("Client connected from %s", r.RemoteAddr)
|
|
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", "*")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
|
|
|
clientChan := make(chan string)
|
|
|
|
go func() {
|
|
for event := range clientChan {
|
|
fmt.Fprintf(w, "data: %s\n\n", event)
|
|
w.(http.Flusher).Flush()
|
|
}
|
|
}()
|
|
|
|
for {
|
|
select {
|
|
case event := <-eventChan:
|
|
clientChan <- event
|
|
case <-r.Context().Done():
|
|
close(clientChan)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func TriggerHandler(w http.ResponseWriter, r *http.Request) {
|
|
log.Printf("Confetti request received from: %s", r.RemoteAddr)
|
|
eventChan <- "Confetti Triggered!"
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write([]byte("Confetti Triggered"))
|
|
}
|
|
|
|
func main() {
|
|
http.HandleFunc("/events", SSEHandler)
|
|
http.HandleFunc("/trigger", TriggerHandler)
|
|
|
|
log.Println("Server running on port 7070")
|
|
log.Fatal(http.ListenAndServe(":7070", nil))
|
|
}
|