This repository has been archived by the owner on Sep 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
map.go
59 lines (50 loc) · 1.92 KB
/
map.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 tripperware
import (
"context"
"net/http"
http_ctxtags "github.com/improbable-eng/go-httpwares/tags"
"github.com/improbable-eng/kedge/pkg/http/ctxtags"
kedge_map "github.com/improbable-eng/kedge/pkg/map"
"github.com/pkg/errors"
)
// routeContextKey specifies the key that route is stored inside request's context.
// if no route is found the nil route is stored.
const routeContextKey = "proxy-route"
func getRoute(ctx context.Context) (*kedge_map.Route, bool, error) {
r, ok := ctx.Value(routeContextKey).(*kedge_map.Route)
if !ok {
// Unit tests should catch that.
return nil, false, errors.New("InternalError: Tripperware misconfiguration. MappingTripper was not before current tripper.")
}
return r, r != nil, nil
}
type mappingTripper struct {
mapper kedge_map.Mapper
parent http.RoundTripper
}
func requestWithRoute(req *http.Request, r *kedge_map.Route) *http.Request {
return req.WithContext(context.WithValue(req.Context(), routeContextKey, r))
}
func (t *mappingTripper) RoundTrip(req *http.Request) (*http.Response, error) {
// Get routing based on request Host and optional port.
route, err := t.mapper.Map(req.URL.Hostname(), req.URL.Port())
if kedge_map.IsNotKedgeDestinationError(err) {
tags := http_ctxtags.ExtractInbound(req)
tags.Set(ctxtags.TagForProxyDestURL, "not-kedge-destination")
return t.parent.RoundTrip(
// We store nil to ensure that we can catch case when mappingTripper is not in the chain before other trippers
// that requires stored route.
requestWithRoute(req, nil),
)
}
if err != nil {
closeIfNotNil(req.Body)
return nil, errors.Wrapf(err, "mappingTripper: Failed to map host %s and port %s into route", req.URL.Hostname(), req.URL.Port())
}
return t.parent.RoundTrip(
requestWithRoute(req, route),
)
}
func WrapForMapping(mapper kedge_map.Mapper, parentTransport http.RoundTripper) http.RoundTripper {
return &mappingTripper{mapper: mapper, parent: parentTransport}
}