This repository has been archived by the owner on Nov 6, 2018. It is now read-only.
forked from cloudfoundry/logging-route-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
106 lines (88 loc) · 2.38 KB
/
main.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
99
100
101
102
103
104
105
106
package main
import (
"crypto/tls"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"time"
)
const (
DEFAULT_PORT = "8080"
CF_FORWARDED_URL_HEADER = "X-Cf-Forwarded-Url"
CF_PROXY_SIGNATURE_HEADER = "X-Cf-Proxy-Signature"
)
func main() {
var (
port string
skipSslValidation bool
err error
)
if port = os.Getenv("PORT"); len(port) == 0 {
port = DEFAULT_PORT
}
if skipSslValidation, err = strconv.ParseBool(os.Getenv("SKIP_SSL_VALIDATION")); err != nil {
skipSslValidation = true
}
log.SetOutput(os.Stdout)
roundTripper := NewDelayRoundTripper(skipSslValidation)
proxy := NewProxy(roundTripper, skipSslValidation)
log.Fatal(http.ListenAndServe(":"+port, proxy))
}
func NewProxy(transport http.RoundTripper, skipSslValidation bool) http.Handler {
reverseProxy := &httputil.ReverseProxy{
Director: func(req *http.Request) {
forwardedURL := req.Header.Get(CF_FORWARDED_URL_HEADER)
logRequest(req.Header, skipSslValidation)
// Note that url.Parse is decoding any url-encoded characters.
url, err := url.Parse(forwardedURL)
if err != nil {
log.Fatalln(err.Error())
}
req.URL = url
req.Host = url.Host
delayRequest(req)
},
Transport: transport,
FlushInterval: 50 * time.Millisecond,
}
return reverseProxy
}
func logRequest(headers http.Header, skipSslValidation bool) {
log.Printf("Skip ssl validation set to %t", skipSslValidation)
log.Println("Received request: ")
log.Println("")
log.Printf("Headers: %#v\n", headers)
log.Println("")
}
type DelayRoundTripper struct {
transport http.RoundTripper
}
func NewDelayRoundTripper(skipSslValidation bool) http.RoundTripper {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: skipSslValidation},
}
return &DelayRoundTripper{
transport: tr,
}
}
func (lrt *DelayRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
res, err := lrt.transport.RoundTrip(request)
if request.URL.Path == "/routing/v1/tcp_routes" {
sleep()
}
return res, err
}
func delayRequest(req *http.Request) {
if req.URL.Path == "/routing/v1/tcp_routes" {
sleep()
}
}
func sleep() {
sleepMilliString := os.Getenv("ROUTE_SERVICE_SLEEP_MILLI")
sleepMilli, _ := strconv.ParseInt(sleepMilliString, 0, 64)
log.Printf("Sleeping for %d milliseconds\n", sleepMilli)
time.Sleep(time.Duration(sleepMilli) * time.Millisecond)
}