-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
76 lines (55 loc) · 1.22 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
package main
import (
"io"
"log"
"math/rand"
"net/http"
)
var Servers = []string{
"localhost:8081",
"localhost:8082",
"localhost:8083",
}
var customTransport = http.DefaultTransport
func chooseServer() string {
r := rand.New(rand.NewSource(99))
randomNumber := r.Intn(len(Servers))
return Servers[randomNumber]
}
func proxyHandler(w http.ResponseWriter, r *http.Request) {
// Choose server
server := chooseServer()
// Create request
req, err := http.NewRequest(r.Method, "http://"+server+r.URL.String(), r.Body)
if err != nil {
log.Println(err)
return
}
// Copy headers
for k, v := range r.Header {
req.Header.Set(k, v[0])
}
// Make request
resp, err := customTransport.RoundTrip(req)
if err != nil {
log.Println(err)
return
}
defer resp.Body.Close()
// Copy headers
for k, v := range resp.Header {
w.Header().Set(k, v[0])
}
// Copy status code
w.WriteHeader(resp.StatusCode)
// Copy body
io.Copy(w, resp.Body)
log.Print("Proxying request to " + server)
log.Print("Request: " + r.URL.String())
log.Print("Response: " + resp.Status)
}
func main() {
http.HandleFunc("/", proxyHandler)
log.Println("Starting proxy server on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}