2023-12-01 12:35:51 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
type streamer struct {
|
|
|
|
templates map[string]*template.Template
|
|
|
|
writer gin.ResponseWriter
|
|
|
|
mutex sync.Mutex
|
|
|
|
completeCh chan struct{}
|
|
|
|
}
|
|
|
|
|
2024-01-20 19:26:26 +00:00
|
|
|
func (api *API) newStreamer(c *gin.Context, data string) *streamer {
|
2023-12-01 12:35:51 +00:00
|
|
|
stream := &streamer{
|
|
|
|
writer: c.Writer,
|
2024-02-25 19:54:50 +00:00
|
|
|
templates: api.templates,
|
2023-12-01 12:35:51 +00:00
|
|
|
completeCh: make(chan struct{}),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set Headers
|
|
|
|
header := stream.writer.Header()
|
|
|
|
header.Set("Transfer-Encoding", "chunked")
|
|
|
|
header.Set("Content-Type", "text/html; charset=utf-8")
|
|
|
|
header.Set("X-Content-Type-Options", "nosniff")
|
|
|
|
stream.writer.WriteHeader(http.StatusOK)
|
|
|
|
|
|
|
|
// Send Open Element Tags
|
2024-01-20 19:26:26 +00:00
|
|
|
stream.write(data)
|
2023-12-01 12:35:51 +00:00
|
|
|
|
|
|
|
// Keep Alive
|
|
|
|
go func() {
|
|
|
|
closeCh := stream.writer.CloseNotify()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-stream.completeCh:
|
|
|
|
return
|
|
|
|
case <-closeCh:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
stream.write("<!-- ping -->")
|
|
|
|
time.Sleep(2 * time.Second)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return stream
|
|
|
|
}
|
|
|
|
|
|
|
|
func (stream *streamer) write(str string) {
|
|
|
|
stream.mutex.Lock()
|
|
|
|
stream.writer.WriteString(str)
|
|
|
|
stream.writer.(http.Flusher).Flush()
|
|
|
|
stream.mutex.Unlock()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (stream *streamer) send(templateName string, templateVars gin.H) {
|
|
|
|
t := stream.templates[templateName]
|
|
|
|
buf := &bytes.Buffer{}
|
|
|
|
_ = t.ExecuteTemplate(buf, templateName, templateVars)
|
|
|
|
stream.write(buf.String())
|
|
|
|
}
|
|
|
|
|
2024-01-20 19:26:26 +00:00
|
|
|
func (stream *streamer) close(data string) {
|
2023-12-01 12:35:51 +00:00
|
|
|
// Send Close Element Tags
|
2024-01-20 19:26:26 +00:00
|
|
|
stream.write(data)
|
2023-12-01 12:35:51 +00:00
|
|
|
|
|
|
|
// Close
|
|
|
|
close(stream.completeCh)
|
|
|
|
}
|