forked from luraproject/lura
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint.go
38 lines (32 loc) · 1.06 KB
/
endpoint.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
// SPDX-License-Identifier: Apache-2.0
package chi
import (
"net/http"
"strings"
"github.com/davron112/lura/config"
"github.com/davron112/lura/proxy"
"github.com/davron112/lura/router/mux"
"github.com/go-chi/chi"
)
// HandlerFactory creates a handler function that adapts the chi router with the injected proxy
type HandlerFactory func(*config.EndpointConfig, proxy.Proxy) http.HandlerFunc
// NewEndpointHandler implements the HandleFactory interface using the default ToHTTPError function
func NewEndpointHandler(cfg *config.EndpointConfig, prxy proxy.Proxy) http.HandlerFunc {
hf := mux.CustomEndpointHandler(
mux.NewRequestBuilder(func(r *http.Request) map[string]string {
return extractParamsFromEndpoint(r)
}),
)
return hf(cfg, prxy)
}
func extractParamsFromEndpoint(r *http.Request) map[string]string {
ctx := r.Context()
rctx := chi.RouteContext(ctx)
params := map[string]string{}
if len(rctx.URLParams.Keys) > 0 {
for _, param := range rctx.URLParams.Keys {
params[strings.Title(param[:1])+param[1:]] = chi.URLParam(r, param)
}
}
return params
}