-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_factory.go
59 lines (54 loc) · 1.66 KB
/
proxy_factory.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 shadowproxy
import (
"regexp"
"strings"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/encoding"
"github.com/luraproject/lura/v2/proxy"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func ProxyFactory(pf proxy.Factory) proxy.FactoryFunc {
return func(cfg *config.EndpointConfig) (proxy.Proxy, error) {
next, err := pf.New(cfg)
if err != nil {
panic(err)
}
prxCfg, ok := configGetter(cfg)
if !ok {
return next, nil
}
shadowProxy, err := pf.New(shadowConfig(*cfg, *prxCfg))
if err != nil {
panic(err)
}
return proxy.ShadowMiddlewareWithTimeout(prxCfg.Timeout, next, shadowProxy), nil
}
}
func shadowConfig(cfg config.EndpointConfig, prxCfg ProxyConfig) *config.EndpointConfig { // nolint
urlPattern, urlKeys := parseURLPattern(prxCfg.URLPattern)
cfg.Backend = []*config.Backend{{
Host: prxCfg.Host,
Method: prxCfg.Method,
URLPattern: urlPattern,
HostSanitizationDisabled: prxCfg.HostSanitizationDisabled,
URLKeys: urlKeys,
Encoding: encoding.NOOP,
Timeout: prxCfg.Timeout,
}}
return &cfg
}
func parseURLPattern(urlPattern string) (string, []string) { // nolint
re := regexp.MustCompile(`/\{([a-zA-Z\-_0-9]+)\}`)
urlKeys := []string{}
if matches := re.FindAllStringSubmatch(urlPattern, -1); matches != nil {
title := cases.Title(language.Und)
for _, v := range matches {
key := v[1]
titleKey := title.String(key[:1]) + key[1:]
urlPattern = strings.ReplaceAll(urlPattern, "{"+key+"}", "{{."+titleKey+"}}")
urlKeys = append(urlKeys, titleKey)
}
}
return urlPattern, urlKeys
}