-
Notifications
You must be signed in to change notification settings - Fork 117
/
fasthttp.go
98 lines (82 loc) · 2.62 KB
/
fasthttp.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
package xray
import (
"context"
"fmt"
"net/http"
"net/url"
"github.com/aws/aws-xray-sdk-go/header"
"github.com/valyala/fasthttp"
)
type FastHTTPHandler interface {
Handler(SegmentNamer, fasthttp.RequestHandler) fasthttp.RequestHandler
}
type fasthttpHandler struct {
cfg *Config
}
// NewFastHTTPInstrumentor returns a struct that provides Handle method
// that satisfy fasthttp.RequestHandler interface.
func NewFastHTTPInstrumentor(cfg *Config) FastHTTPHandler {
return &fasthttpHandler{
cfg: cfg,
}
}
// Handler wraps the provided fasthttp.RequestHandler
func (h *fasthttpHandler) Handler(sn SegmentNamer, handler fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
auxCtx := context.Background()
if h.cfg != nil {
auxCtx = context.WithValue(context.Background(), fasthttpContextConfigKey, h.cfg)
ctx.SetUserValue(fasthttpContextConfigKey, h.cfg)
}
name := sn.Name(string(ctx.Request.Host()))
traceHeader := header.FromString(string(ctx.Request.Header.Peek(TraceIDHeaderKey)))
req, err := fasthttpToNetHTTPRequest(ctx)
if err != nil {
ctx.Logger().Printf("%s", err.Error())
ctx.Error("Internal Server Error", fasthttp.StatusInternalServerError)
return
}
_, seg := NewSegmentFromHeader(auxCtx, name, req, traceHeader)
defer seg.Close(nil)
ctx.SetUserValue(fasthttpContextKey, seg)
httpCaptureRequest(seg, req)
fasthttpTrace(seg, handler, ctx, traceHeader)
}
}
// fasthttpToNetHTTPRequest convert a fasthttp.Request to http.Request
func fasthttpToNetHTTPRequest(ctx *fasthttp.RequestCtx) (*http.Request, error) {
requestURI := string(ctx.RequestURI())
rURL, err := url.ParseRequestURI(requestURI)
if err != nil {
return nil, fmt.Errorf("cannot parse requestURI %q: %s", requestURI, err)
}
req := &http.Request{
URL: rURL,
Host: string(ctx.Host()),
RequestURI: requestURI,
Method: string(ctx.Method()),
RemoteAddr: ctx.RemoteAddr().String(),
}
hdr := make(http.Header)
ctx.Request.Header.VisitAll(func(k, v []byte) {
sk := string(k)
sv := string(v)
switch sk {
case "Transfer-Encoding":
req.TransferEncoding = append(req.TransferEncoding, sv)
default:
hdr.Set(sk, sv)
}
})
req.Header = hdr
req.TLS = ctx.TLSConnectionState()
return req, nil
}
func fasthttpTrace(seg *Segment, h fasthttp.RequestHandler, ctx *fasthttp.RequestCtx, traceHeader *header.Header) {
ctx.Request.Header.Set(TraceIDHeaderKey, generateTraceIDHeaderValue(seg, traceHeader))
h(ctx)
seg.Lock()
seg.GetHTTP().GetResponse().ContentLength = ctx.Response.Header.ContentLength()
seg.Unlock()
HttpCaptureResponse(seg, ctx.Response.StatusCode())
}