2024-06-04 00:15:07 +07:00
|
|
|
package events
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2024-06-10 14:52:53 +07:00
|
|
|
"strings"
|
2024-06-04 00:15:07 +07:00
|
|
|
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/log"
|
|
|
|
)
|
|
|
|
|
2024-06-10 14:52:53 +07:00
|
|
|
// SimpleEvents is a simple event stream for the purpose of
|
|
|
|
// notification that something did happen. Not what the content of the event is.
|
|
|
|
//
|
|
|
|
// Useful for simple notification whose client just need to know that something
|
|
|
|
// happened and do something that does not require the content of the event,
|
|
|
|
// like refreshing the list by calling another http request.
|
|
|
|
func (handler *Handler) SimpleEvents(rw http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx, span := tracer.Start(r.Context(), "*Routes.SimpleDownloadEvent")
|
2024-06-04 00:15:07 +07:00
|
|
|
defer span.End()
|
|
|
|
|
|
|
|
flush, ok := rw.(http.Flusher)
|
|
|
|
if !ok {
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
|
|
|
_ = json.NewEncoder(rw).Encode(map[string]string{"error": "response writer does not support streaming"})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-06-10 23:36:26 +07:00
|
|
|
var filters []string
|
|
|
|
if q := r.URL.Query().Get("filter"); q != "" {
|
|
|
|
filters = strings.Split(q, ",")
|
|
|
|
}
|
2024-06-10 14:52:53 +07:00
|
|
|
|
2024-06-04 00:15:07 +07:00
|
|
|
log.New(ctx).Info("new simple event stream connection", "user_agent", r.UserAgent())
|
|
|
|
|
|
|
|
rw.Header().Set("Content-Type", "text/event-stream")
|
|
|
|
rw.Header().Set("Cache-Control", "no-cache")
|
|
|
|
rw.Header().Set("Connection", "keep-alive")
|
|
|
|
rw.WriteHeader(200)
|
|
|
|
flush.Flush()
|
|
|
|
|
|
|
|
ev, close := handler.Subscribe()
|
|
|
|
defer close()
|
|
|
|
|
2024-06-10 14:52:53 +07:00
|
|
|
loop:
|
2024-06-04 00:15:07 +07:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-r.Context().Done():
|
|
|
|
log.New(ctx).Info("simple event stream connection closed", "user_agent", r.UserAgent())
|
|
|
|
return
|
|
|
|
case event := <-ev:
|
|
|
|
msg := event.Event()
|
2024-06-10 14:52:53 +07:00
|
|
|
for _, filter := range filters {
|
|
|
|
if filter != msg {
|
|
|
|
continue loop
|
|
|
|
}
|
|
|
|
}
|
2024-06-04 00:15:07 +07:00
|
|
|
if _, err := fmt.Fprintf(rw, "event: %s\ndata: %s\n\n", msg, msg); err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
flush.Flush()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|