forked from si74/layer7lb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (67 loc) · 1.92 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
package main
import (
"fmt"
"io"
"log"
"math/rand"
"net/http"
)
// TODO(sneha): make backends configurable.
var (
backends = []string{"cnn.com", "bbc.co.uk", "msn.com"}
)
func main() {
// TODO(sneha) Validate backends/transform into valid list.
// Create global client.
// TODO(sneha): configure with more options.
client := http.Client{}
// HTTP handler and server.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Randomly select from list of backends.
n := rand.Intn(len(backends))
// TODO(sneha): provide hostname and port, scheme for backends
// How do real lbs handle this?
// HTTP client is limiting us but realy want to demarcate
// a - which host to send the request to vs.
// b - which host is in the header that we want to maintain
fmt.Println(r)
fmt.Println(r.URL.String())
r.URL.Host = backends[n]
r.URL.Scheme = "https"
fmt.Println(r.URL.String())
req, err := http.NewRequest(r.Method, r.URL.String(), r.Body)
if err != nil {
// TODO(sneha): fix how this returns later.
http.Error(w, "cannot process request", http.StatusBadGateway)
return
}
for key, vals := range r.Header {
for _, val := range vals {
req.Header.Add(key, val)
}
}
res, err := client.Do(req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer res.Body.Close()
if res.StatusCode/100 == 5 {
http.Error(w, fmt.Sprintf("backend returns status code: %s", res.Status), http.StatusBadGateway)
return
}
for key, vals := range res.Header {
for _, val := range vals {
w.Header().Add(key, val)
}
}
w.WriteHeader(res.StatusCode)
// TODO(sneha): Split into ioutil.Readall and therefore be able to
// differentiate and clearly demarcate what the error is.
_, err = io.Copy(w, res.Body)
if err != nil {
log.Printf("error writing response to client: %v", err)
}
})
log.Fatal(http.ListenAndServe(":8080", nil))
}