golang + sse + Data-Star for real time progress bar
Hello everyone, somtimes happens, that one request could block whole page for minutes with heavy on demand job. And thats not good. But with data-star its very simple to give user realtime feedback about whats happenining. here is tiny code example: r.Post("/progress", func(w http.ResponseWriter, r *http.Request) { sse := datastar.NewSSE(w, r) progress := 0 total := 10124 processed := 0 for { select { case

Hello everyone,
somtimes happens, that one request could block whole page for minutes with heavy on demand job. And thats not good. But with data-star its very simple to give user realtime feedback about whats happenining.
here is tiny code example:
r.Post("/progress", func(w http.ResponseWriter, r *http.Request) {
sse := datastar.NewSSE(w, r)
progress := 0
total := 10124
processed := 0
for {
select {
case <-r.Context().Done():
return
default:
processed++
progress = (processed * 100 / total)
// lets say here is our heavy job function which is slow but after each step we notify user with progress
time.Sleep(1 * time.Millisecond)
// send updates to frontend via SSE
sse.MergeFragmentTempl(Progress(fmt.Sprintf("%d", processed), fmt.Sprintf("%d", total), fmt.Sprintf("%d", progress)))
if progress == 100 {
sse.MergeFragmentTempl(Done())
return
}
}
}
})
whats nice about DataStar and SSE that each GET PUT POST PATCH DELETE requests could respond N events stream in realtime while doing heavy work, so user always can see progress of whats happening.
heres full working code repo: https://github.com/blinkinglight/go-progressbar