-
-
Notifications
You must be signed in to change notification settings - Fork 341
Expand file tree
/
Copy pathhandler.go
More file actions
99 lines (77 loc) · 2.37 KB
/
handler.go
File metadata and controls
99 lines (77 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package mercure
import (
"io/fs"
"log/slog"
"net/http"
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/unrolled/secure"
)
const (
defaultHubURL = "/.well-known/mercure"
defaultUIURL = defaultHubURL + "/ui/"
defaultDemoURL = defaultUIURL + "demo/"
)
func (h *Hub) initHandler() {
router := mux.NewRouter()
router.UseEncodedPath()
router.SkipClean(true)
csp := "default-src 'self'"
if h.demo {
router.PathPrefix(defaultDemoURL).HandlerFunc(h.Demo).Methods(http.MethodGet, http.MethodHead)
}
if h.ui {
public, err := fs.Sub(uiContent, "public")
if err != nil {
panic(err)
}
router.PathPrefix(defaultUIURL).Handler(http.StripPrefix(defaultUIURL, http.FileServer(http.FS(public))))
csp += " mercure.rocks cdn.jsdelivr.net"
}
h.registerSubscriptionHandlers(router)
if h.subscriberJWTKeyFunc != nil || h.anonymous {
router.HandleFunc(defaultHubURL, h.SubscribeHandler).Methods(http.MethodGet, http.MethodHead)
}
if h.publisherJWTKeyFunc != nil {
router.HandleFunc(defaultHubURL, h.PublishHandler).Methods(http.MethodPost)
}
secureMiddleware := secure.New(secure.Options{
IsDevelopment: h.debug,
AllowedHosts: h.allowedHosts,
FrameDeny: true,
ContentTypeNosniff: true,
BrowserXssFilter: true,
ContentSecurityPolicy: csp,
})
if len(h.corsOrigins) == 0 {
h.handler = secureMiddleware.Handler(router)
return
}
h.handler = secureMiddleware.Handler(
cors.New(cors.Options{
AllowedOrigins: h.corsOrigins,
AllowCredentials: true,
AllowedHeaders: []string{"authorization", "cache-control", "last-event-id"},
Debug: h.debug,
}).Handler(router),
)
}
func (h *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handler.ServeHTTP(w, r)
}
func (h *Hub) registerSubscriptionHandlers(r *mux.Router) {
if !h.subscriptions {
return
}
if _, ok := h.transport.(TransportSubscribers); !ok {
if h.logger.Enabled(h.ctx, slog.LevelError) {
h.logger.LogAttrs(h.ctx, slog.LevelError, "The current transport doesn't support subscriptions. Subscription API disabled.")
}
return
}
r.UseEncodedPath()
r.SkipClean(true)
r.HandleFunc(subscriptionURL, h.SubscriptionHandler).Methods(http.MethodGet)
r.HandleFunc(subscriptionsForTopicURL, h.SubscriptionsHandler).Methods(http.MethodGet)
r.HandleFunc(subscriptionsURL, h.SubscriptionsHandler).Methods(http.MethodGet)
}