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
/
route.go
47 lines (40 loc) · 1.67 KB
/
route.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
package tripperware
import (
"net/http"
http_ctxtags "github.com/improbable-eng/go-httpwares/tags"
"github.com/improbable-eng/kedge/pkg/http/ctxtags"
"github.com/pkg/errors"
)
// routingTripper is a piece of tripperware that dials certain destinations (indicated by a route stored in request's context) through a remote proxy (kedge).
// The dialing is performed in a "reverse proxy" fashion, where the Host header indicates to the kedge what backend
// to dial.
// NOTE: It requires to have mappingTripper before itself to put the routing inside context.
type routingTripper struct {
parent http.RoundTripper
}
func (t *routingTripper) RoundTrip(req *http.Request) (*http.Response, error) {
route, ok, err := getRoute(req.Context())
if err != nil {
closeIfNotNil(req.Body)
return nil, errors.Wrap(err, "routingTripper: Failed to get route from context")
}
if !ok {
return t.parent.RoundTrip(req)
}
// TODO(bplotka): Pack some cache for kedge DNS resolution. It does not change much after winch startup.
destURL := route.URL
tags := http_ctxtags.ExtractInbound(req)
tags.Set(ctxtags.TagForProxyDestURL, destURL)
tags.Set(http_ctxtags.TagForHandlerName, destURL)
// Copy the URL and the request to not override the callers info.
copyUrl := *req.URL
copyUrl.Scheme = destURL.Scheme
copyUrl.Host = destURL.Host
copyReq := req.WithContext(req.Context()) // makes a copy
copyReq.URL = &(copyUrl) // shallow copy
copyReq.Host = req.URL.Host // store the original host (+ optional :port)
return t.parent.RoundTrip(copyReq)
}
func WrapForRouting(parentTransport http.RoundTripper) http.RoundTripper {
return &routingTripper{parent: parentTransport}
}