-
Notifications
You must be signed in to change notification settings - Fork 34
/
proxy.go
63 lines (56 loc) · 1.51 KB
/
proxy.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
package opencensus
import (
"context"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/proxy"
"go.opencensus.io/trace"
)
const errCtxCanceledMsg = "context canceled"
func Middleware(name string) proxy.Middleware {
if !IsPipeEnabled() {
return proxy.EmptyMiddleware
}
return func(next ...proxy.Proxy) proxy.Proxy {
if len(next) > 1 {
panic(proxy.ErrTooManyProxies)
}
if len(next) < 1 {
panic(proxy.ErrNotEnoughProxies)
}
return func(ctx context.Context, req *proxy.Request) (*proxy.Response, error) {
var span *trace.Span
ctx, span = trace.StartSpan(trace.NewContext(ctx, fromContext(ctx)), name)
resp, err := next[0](ctx, req)
if err != nil {
if err.Error() != errCtxCanceledMsg {
span.AddAttributes(trace.StringAttribute("error", err.Error()))
} else {
span.AddAttributes(trace.BoolAttribute("canceled", true))
}
}
span.AddAttributes(trace.BoolAttribute("complete", resp != nil && resp.IsComplete))
span.End()
return resp, err
}
}
}
func ProxyFactory(pf proxy.Factory) proxy.FactoryFunc {
if !IsPipeEnabled() {
return pf.New
}
return func(cfg *config.EndpointConfig) (proxy.Proxy, error) {
next, err := pf.New(cfg)
if err != nil {
return next, err
}
return Middleware("pipe-" + cfg.Endpoint)(next), nil
}
}
func BackendFactory(bf proxy.BackendFactory) proxy.BackendFactory {
if !IsBackendEnabled() {
return bf
}
return func(cfg *config.Backend) proxy.Proxy {
return Middleware("backend-" + cfg.URLPattern)(bf(cfg))
}
}