39 lines
924 B
Go
39 lines
924 B
Go
|
|
package nebula
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"nebula/htmx"
|
||
|
|
"nebula/pkg/config"
|
||
|
|
)
|
||
|
|
|
||
|
|
func Middleware(opts ...Option) func(http.Handler) http.Handler {
|
||
|
|
cfg := DefaultConfig()
|
||
|
|
for _, opt := range opts {
|
||
|
|
opt(&cfg)
|
||
|
|
}
|
||
|
|
|
||
|
|
return func(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
hxCtx := htmx.ExtractContext(r)
|
||
|
|
ctx := htmx.WithContext(r.Context(), hxCtx)
|
||
|
|
ctx = config.WithContext(ctx, &cfg)
|
||
|
|
|
||
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func SSEMiddleware() func(http.Handler) http.Handler {
|
||
|
|
return func(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
if r.Header.Get("Accept") == "text/event-stream" {
|
||
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
||
|
|
w.Header().Set("Cache-Control", "no-cache")
|
||
|
|
w.Header().Set("Connection", "keep-alive")
|
||
|
|
}
|
||
|
|
next.ServeHTTP(w, r)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|