-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
requestHandler.go
231 lines (211 loc) · 8.95 KB
/
requestHandler.go
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package service
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/plgd-dev/hub/v2/grpc-gateway/client"
"github.com/plgd-dev/hub/v2/grpc-gateway/pb"
"github.com/plgd-dev/hub/v2/http-gateway/grpc-websocket-proxy/wsproxy"
"github.com/plgd-dev/hub/v2/http-gateway/serverMux"
"github.com/plgd-dev/hub/v2/http-gateway/uri"
"github.com/plgd-dev/hub/v2/pkg/log"
kitHttp "github.com/plgd-dev/hub/v2/pkg/net/http"
"github.com/plgd-dev/hub/v2/pkg/security/openid"
pkgStrings "github.com/plgd-dev/hub/v2/pkg/strings"
)
// RequestHandler for handling incoming request
type RequestHandler struct {
client *client.Client
config *Config
mux *runtime.ServeMux
openIDConfig openid.Config
logger log.Logger
}
func matchPrefixAndSplitURIPath(requestURI, prefix string) []string {
if len(requestURI) == 0 {
return nil
}
v := kitHttp.CanonicalHref(requestURI)
p := strings.TrimPrefix(v, prefix) // remove core prefix
if p == v {
return nil
}
p = strings.TrimLeft(p, "/")
return strings.Split(p, "/")
}
func unescapeString(s string) string {
newS, err := pkgStrings.Unescape(s, pkgStrings.UnescapingModeAllCharacters, false)
if err != nil {
return s
}
return newS
}
func resourcePendingCommandsMatcher(r *http.Request, rm *mux.RouteMatch) bool {
paths := matchPrefixAndSplitURIPath(r.RequestURI, uri.Devices)
if len(paths) > 3 && paths[1] == uri.ResourcesPathKey && strings.Contains(paths[len(paths)-1], uri.PendingCommandsPathKey) {
if rm.Vars == nil {
rm.Vars = make(map[string]string)
}
rm.Vars[uri.DeviceIDKey] = unescapeString(paths[0])
rm.Vars[uri.ResourceHrefKey] = unescapeString(strings.Split("/"+strings.Join(paths[2:len(paths)-1], "/"), "?")[0])
return true
}
if len(paths) > 4 && paths[1] == uri.ResourcesPathKey && strings.Contains(paths[len(paths)-2], uri.PendingCommandsPathKey) {
if rm.Vars == nil {
rm.Vars = make(map[string]string)
}
rm.Vars[uri.DeviceIDKey] = unescapeString(paths[0])
rm.Vars[uri.ResourceHrefKey] = unescapeString("/" + strings.Join(paths[2:len(paths)-2], "/"))
rm.Vars[uri.CorrelationIDKey] = strings.Split(paths[len(paths)-1], "?")[0]
return true
}
return false
}
func resourceMatcher(r *http.Request, rm *mux.RouteMatch) bool {
paths := matchPrefixAndSplitURIPath(r.RequestURI, uri.Devices)
if len(paths) > 2 &&
paths[1] == uri.ResourcesPathKey &&
!strings.HasPrefix(paths[len(paths)-1], uri.EventsPathKey) {
if rm.Vars == nil {
rm.Vars = make(map[string]string)
}
rm.Vars[uri.DeviceIDKey] = unescapeString(paths[0])
rm.Vars[uri.ResourceHrefKey] = unescapeString(strings.Split("/"+strings.Join(paths[2:], "/"), "?")[0])
return true
}
return false
}
func resourceLinksMatcher(r *http.Request, rm *mux.RouteMatch) bool {
paths := matchPrefixAndSplitURIPath(r.RequestURI, uri.Devices)
if len(paths) > 2 && paths[1] == uri.ResourceLinksPathKey {
if rm.Vars == nil {
rm.Vars = make(map[string]string)
}
rm.Vars[uri.DeviceIDKey] = unescapeString(paths[0])
rm.Vars[uri.ResourceHrefKey] = unescapeString(strings.Split("/"+strings.Join(paths[2:], "/"), "?")[0])
return true
}
return false
}
func resourceEventsMatcher(r *http.Request, rm *mux.RouteMatch) bool {
paths := matchPrefixAndSplitURIPath(r.RequestURI, uri.Devices)
// /api/v1/devices/{deviceId}/resources/{resourceHref}/events
// /api/v1/devices/{deviceId}/resources/{resourceHref}/events?timestampFilter={timestamp}
if len(paths) > 3 &&
paths[1] == uri.ResourcesPathKey &&
strings.HasPrefix(paths[len(paths)-1], uri.EventsPathKey) {
if rm.Vars == nil {
rm.Vars = make(map[string]string)
}
rm.Vars[uri.DeviceIDKey] = unescapeString(paths[0])
rm.Vars[uri.ResourceHrefKey] = unescapeString("/" + strings.Join(paths[2:len(paths)-1], "/"))
return true
}
return false
}
func thingMatcher(r *http.Request, rm *mux.RouteMatch) bool {
// /api/v1/things/{deviceId}
paths := matchPrefixAndSplitURIPath(r.RequestURI, uri.Things)
if len(paths) == 1 {
if rm.Vars == nil {
rm.Vars = make(map[string]string)
}
rm.Vars[uri.DeviceIDKey] = unescapeString(paths[0])
return true
}
return false
}
func wsRequestMutator(incoming, outgoing *http.Request) *http.Request {
outgoing.Method = http.MethodPost
accept := getAccept(incoming)
if accept != "" {
outgoing.Header.Set(uri.AcceptHeaderKey, accept)
}
if incoming.RequestURI == uri.SubscribeToEvents {
contentType := incoming.Header.Get(uri.ContentTypeHeaderKey)
if contentType == uri.ApplicationProtoJsonContentType {
outgoing.Header.Set(uri.ContentTypeHeaderKey, ApplicationSubscribeToEventsProtoJsonContentType)
} else {
outgoing.Header.Set(uri.ContentTypeHeaderKey, ApplicationSubscribeToEventsMIMEWildcard)
}
}
return outgoing
}
func (requestHandler *RequestHandler) setupUIHandler(r *mux.Router) {
r.HandleFunc(uri.WebConfiguration, requestHandler.getWebConfiguration).Methods(http.MethodGet)
fs := http.FileServer(http.Dir(requestHandler.config.UI.Directory))
r.PathPrefix("/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c := httptest.NewRecorder()
fs.ServeHTTP(c, r)
if c.Code == http.StatusNotFound {
c = httptest.NewRecorder()
r.URL.Path = "/"
fs.ServeHTTP(c, r)
}
for k, v := range c.Header() {
w.Header().Set(k, strings.Join(v, ""))
}
w.WriteHeader(c.Code)
if _, err := c.Body.WriteTo(w); err != nil {
log.Errorf("failed to write response body: %w", err)
}
}))
}
// NewHTTP returns HTTP handler
func NewRequestHandler(config *Config, r *mux.Router, client *client.Client, openIDConfig openid.Config, logger log.Logger) (*RequestHandler, error) {
requestHandler := &RequestHandler{
client: client,
config: config,
openIDConfig: openIDConfig,
logger: logger,
mux: serverMux.New(
runtime.WithMarshalerOption(ApplicationSubscribeToEventsMIMEWildcard, newSubscribeToEventsMarshaler(serverMux.NewJsonMarshaler())),
runtime.WithMarshalerOption(ApplicationSubscribeToEventsProtoJsonContentType, serverMux.NewJsonpbMarshaler()),
),
}
// Aliases
r.HandleFunc(uri.AliasDevice, requestHandler.getDevice).Methods(http.MethodGet)
r.HandleFunc(uri.AliasDevice, requestHandler.deleteDevice).Methods(http.MethodDelete)
r.HandleFunc(uri.AliasDeviceResourceLinks, requestHandler.getDeviceResourceLinks).Methods(http.MethodGet)
r.HandleFunc(uri.AliasDeviceResources, requestHandler.getDeviceResources).Methods(http.MethodGet)
r.HandleFunc(uri.AliasDevicePendingCommands, requestHandler.getDevicePendingCommands).Methods(http.MethodGet)
r.HandleFunc(uri.AliasDevicePendingMetadataUpdates, requestHandler.getPendingMetadataUpdates).Methods(http.MethodGet)
r.HandleFunc(uri.AliasDevicePendingMetadataUpdate, requestHandler.cancelPendingMetadataUpdate).Methods(http.MethodDelete)
r.HandleFunc(uri.AliasDeviceEvents, requestHandler.getEvents).Methods(http.MethodGet)
r.HandleFunc(uri.Configuration, requestHandler.getHubConfiguration).Methods(http.MethodGet)
r.HandleFunc(uri.HubConfiguration, requestHandler.getHubConfiguration).Methods(http.MethodGet)
r.HandleFunc(uri.Things, requestHandler.getThings).Methods(http.MethodGet)
r.PathPrefix(uri.Devices).Methods(http.MethodPost).MatcherFunc(resourceLinksMatcher).HandlerFunc(requestHandler.createResource)
r.PathPrefix(uri.Devices).Methods(http.MethodGet).MatcherFunc(resourcePendingCommandsMatcher).HandlerFunc(requestHandler.getResourcePendingCommands)
r.PathPrefix(uri.Devices).Methods(http.MethodDelete).MatcherFunc(resourcePendingCommandsMatcher).HandlerFunc(requestHandler.CancelPendingCommands)
r.PathPrefix(uri.Devices).Methods(http.MethodGet).MatcherFunc(resourceMatcher).HandlerFunc(requestHandler.getResource)
r.PathPrefix(uri.Devices).Methods(http.MethodPut).MatcherFunc(resourceMatcher).HandlerFunc(requestHandler.updateResource)
r.PathPrefix(uri.Devices).Methods(http.MethodGet).MatcherFunc(resourceEventsMatcher).HandlerFunc(requestHandler.getEvents)
r.PathPrefix(uri.Things).Methods(http.MethodGet).MatcherFunc(thingMatcher).HandlerFunc(requestHandler.getThing)
// register grpc-proxy handler
if err := pb.RegisterGrpcGatewayHandlerClient(context.Background(), requestHandler.mux, requestHandler.client.GrpcGatewayClient()); err != nil {
return nil, fmt.Errorf("failed to register grpc-gateway handler: %w", err)
}
// ws grpc-proxy
ws := wsproxy.WebsocketProxy(requestHandler.mux,
wsproxy.WithMaxRespBodyBufferSize(requestHandler.config.APIs.HTTP.WebSocket.StreamBodyLimit),
wsproxy.WithPingControl(requestHandler.config.APIs.HTTP.WebSocket.PingFrequency),
wsproxy.WithRequestMutator(wsRequestMutator))
r.PathPrefix(uri.APIWS + "/").HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ws.ServeHTTP(rw, r)
})
// api grpc-proxy
r.Handle(uri.HubConfiguration, requestHandler.mux)
r.PathPrefix(uri.API + "/").HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
requestHandler.mux.ServeHTTP(rw, r)
})
// serve www directory
if requestHandler.config.UI.Enabled {
requestHandler.setupUIHandler(r)
}
return requestHandler, nil
}