-
Notifications
You must be signed in to change notification settings - Fork 1
/
multi_target_proxy_handler.go
74 lines (66 loc) · 2.18 KB
/
multi_target_proxy_handler.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
package main
import (
"io"
"net/http"
"net/url"
"github.com/Sirupsen/logrus"
)
type MultiTargetProxy struct {
versionProxies map[string]*ReverseProxy
specReference *APISpec
defaultProxy *ReverseProxy
}
func (m *MultiTargetProxy) proxyForRequest(r *http.Request) *ReverseProxy {
version, _, _, _ := m.specReference.Version(r)
if proxy := m.versionProxies[version.Name]; proxy != nil {
return proxy
}
log.WithFields(logrus.Fields{
"prefix": "multi-target",
}).Warning("No proxy found, using default")
return m.defaultProxy
}
func (m *MultiTargetProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) *http.Response {
log.WithFields(logrus.Fields{
"prefix": "multi-target",
}).Debug("Serving Multi-target...")
return m.proxyForRequest(r).ServeHTTP(w, r)
}
func (m *MultiTargetProxy) ServeHTTPForCache(w http.ResponseWriter, r *http.Request) *http.Response {
return m.proxyForRequest(r).ServeHTTPForCache(w, r)
}
func (m *MultiTargetProxy) CopyResponse(dst io.Writer, src io.Reader) {
m.defaultProxy.CopyResponse(dst, src)
}
func NewMultiTargetProxy(spec *APISpec) *MultiTargetProxy {
m := &MultiTargetProxy{}
m.versionProxies = make(map[string]*ReverseProxy)
m.specReference = spec
m.defaultProxy = TykNewSingleHostReverseProxy(spec.target, spec)
for vname, vdata := range spec.VersionData.Versions {
if vdata.OverrideTarget == "" {
log.WithFields(logrus.Fields{
"prefix": "multi-target",
}).Info("----> Version ", vname, " has no override target")
m.versionProxies[vname] = m.defaultProxy
continue
}
remote, err := url.Parse(vdata.OverrideTarget)
log.WithFields(logrus.Fields{
"prefix": "multi-target",
}).Info("----> Version ", vname, " has '", vdata.OverrideTarget, "' for override target")
log.WithFields(logrus.Fields{
"prefix": "multi-target",
}).Debug("Multi-target URL: ", vdata.OverrideTarget)
log.WithFields(logrus.Fields{
"prefix": "multi-target",
}).Debug("Multi-target URL (obj): ", remote)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "multi-target",
}).Error("Couldn't parse version target URL in MultiTarget: ", err)
}
m.versionProxies[vname] = TykNewSingleHostReverseProxy(remote, spec)
}
return m
}