confetti-api/main.go
hook-lord 2bb533736c
All checks were successful
Build and Push / build (push) Successful in 1m31s
logging
2024-09-14 07:08:07 +02:00

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))
}