add sse wrapper
This commit is contained in:
parent
65ef5cb27d
commit
a39a22407f
@ -51,9 +51,17 @@ func DefaultCookieAndRecoveryMiddleware(
|
||||
const headerKey = jwt_adapter.DefaultHeaderKey
|
||||
|
||||
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
|
||||
var err error
|
||||
var (
|
||||
err error
|
||||
tokenHeader string
|
||||
)
|
||||
cookie := &jwt_adapter.JwtAdapter{}
|
||||
tokenHeader := r.Header.Get(headerKey)
|
||||
|
||||
if r.Method == http.MethodGet {
|
||||
tokenHeader = fmt.Sprintf("Bearer %s", r.Form.Get(headerKey))
|
||||
} else {
|
||||
tokenHeader = r.Header.Get(headerKey)
|
||||
}
|
||||
|
||||
if tokenHeader == "" {
|
||||
fmt.Println("ERROR NO authHEader")
|
||||
|
@ -109,3 +109,7 @@ func (h *Heruvym) CreateTicket(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Heruvym) GetList(f http.Flusher, r *http.Request) {
|
||||
|
||||
}
|
||||
|
67
tools/tools.go
Normal file
67
tools/tools.go
Normal file
@ -0,0 +1,67 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dataEmitter func(ctx context.Context) chan interface{}
|
||||
|
||||
func SseWrapper(w http.ResponseWriter, r *http.Request, emitter dataEmitter) {
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(
|
||||
w,
|
||||
"flushing is not allowed",
|
||||
http.StatusFailedDependency,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
dE := emitter(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second * 10):
|
||||
SSEPing(w)
|
||||
case m := <-dE:
|
||||
line, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if _, err := w.Write(
|
||||
[]byte(
|
||||
fmt.Sprintf(
|
||||
"data: %s\n\n",
|
||||
string(line),
|
||||
),
|
||||
),
|
||||
); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sends SSE ping
|
||||
func SSEPing(w http.ResponseWriter) {
|
||||
if _, err := w.Write([]byte(":ping\n\n")); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if flusher, ok := w.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
} else {
|
||||
panic("streaming unsupported")
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user