confetti-api/main.go

52 lines
1.1 KiB
Go
Raw Normal View History

2024-09-13 19:39:16 +00:00
package main
import (
"fmt"
"log"
"net/http"
)
var eventChan = make(chan string)
func SSEHandler(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", "*")
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) {
eventChan <- "Confetti Triggered!"
w.WriteHeader(http.StatusOK)
w.Write([]byte("Confetti Triggered"))
}
func main() {
http.HandleFunc("/events", SSEHandler)
http.HandleFunc("/trigger", TriggerHandler)
2024-09-13 20:52:22 +00:00
log.Println("Server running on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
2024-09-13 19:39:16 +00:00
}