htmgo/framework/h/livereload.go

42 lines
914 B
Go
Raw Normal View History

2024-09-11 00:52:18 +00:00
package h
import (
"fmt"
2024-09-17 17:13:22 +00:00
"github.com/google/uuid"
"net/http"
2024-09-11 00:52:18 +00:00
"time"
)
2024-09-17 17:13:22 +00:00
var Version = uuid.NewString()
func sseHandler(w http.ResponseWriter, r *http.Request) {
// Set the necessary headers
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", "*") // Optional for CORS
// Flush the headers immediately
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
for {
// Write an event to the stream
_, err := fmt.Fprintf(w, "data: %s\n\n", Version)
if err != nil {
break
2024-09-17 17:13:22 +00:00
}
// Flush the response to ensure the client gets it immediately
flusher.Flush()
time.Sleep(500 * time.Millisecond)
}
2024-09-11 00:52:18 +00:00
}
func (app *App) AddLiveReloadHandler(path string) {
app.Router.Get(path, sseHandler)
2024-09-11 00:52:18 +00:00
}