-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
59 lines (48 loc) · 1.13 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
package main
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"time"
)
func main() {
backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "this call was relayed by the reverse proxy")
}))
defer backendServer.Close()
rpURL, err := url.Parse(backendServer.URL)
if err != nil {
log.Fatal(err)
}
randSource := rand.NewSource(time.Now().UnixNano())
randGen := rand.New(randSource)
director := func(req *http.Request) {
var proxyURL *url.URL
if randGen.Intn(100) > 50 {
proxyURL = rpURL
} else {
proxyURL, _ = url.Parse("https://now.httpbin.org/")
}
req.Host = proxyURL.Host
req.URL.Scheme = proxyURL.Scheme
req.URL.Host = proxyURL.Host
go reportAccessTime(proxyURL)
}
reverseProxy := &httputil.ReverseProxy{Director: director}
frontendProxy := httptest.NewServer(reverseProxy)
defer frontendProxy.Close()
resp, err := http.Get(frontendProxy.URL)
if err != nil {
log.Fatal(err)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", b)
}