forked from luraproject/lura
-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.go
59 lines (50 loc) · 1.8 KB
/
router.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
/* Package httptreemux provides some basic implementations for building routers based on dimfeld/httptreemux
*/
// SPDX-License-Identifier: Apache-2.0
package httptreemux
import (
"net/http"
"strings"
"github.com/badboyd/lura/logging"
"github.com/badboyd/lura/proxy"
"github.com/badboyd/lura/router"
"github.com/badboyd/lura/router/mux"
"github.com/dimfeld/httptreemux"
)
// DefaultFactory returns a net/http mux router factory with the injected proxy factory and logger
func DefaultFactory(pf proxy.Factory, logger logging.Logger) router.Factory {
return mux.NewFactory(DefaultConfig(pf, logger))
}
// DefaultConfig returns the struct that collects the parts the router should be built from
func DefaultConfig(pf proxy.Factory, logger logging.Logger) mux.Config {
return mux.Config{
Engine: NewEngine(httptreemux.NewContextMux()),
Middlewares: []mux.HandlerMiddleware{},
HandlerFactory: mux.CustomEndpointHandler(mux.NewRequestBuilder(ParamsExtractor)),
ProxyFactory: pf,
Logger: logger,
DebugPattern: "/__debug/{params}",
RunServer: router.RunServer,
}
}
func ParamsExtractor(r *http.Request) map[string]string {
params := map[string]string{}
for key, value := range httptreemux.ContextParams(r.Context()) {
params[strings.Title(key)] = value
}
return params
}
func NewEngine(m *httptreemux.ContextMux) Engine {
return Engine{m}
}
type Engine struct {
r *httptreemux.ContextMux
}
// Handle implements the mux.Engine interface from the lura router package
func (g Engine) Handle(pattern, method string, handler http.Handler) {
g.r.Handle(method, pattern, handler.(http.HandlerFunc))
}
// ServeHTTP implements the http:Handler interface from the stdlib
func (g Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
g.r.ServeHTTP(mux.NewHTTPErrorInterceptor(w), r)
}