-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatcher.go
71 lines (58 loc) · 1.34 KB
/
dispatcher.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
package main
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
fwd := &forwarder{"api", 8080}
http.Handle("/words/", http.StripPrefix("/words", fwd))
http.Handle("/", http.FileServer(http.Dir("static")))
fmt.Println("Listening on port 80")
http.ListenAndServe(":80", nil)
}
type forwarder struct {
host string
port int
}
func (f *forwarder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
addrs, err := net.LookupHost(f.host)
if err != nil {
log.Println("Error", err)
http.Error(w, err.Error(), 500)
return
}
log.Printf("%s %d available ips: %v", r.URL.Path, len(addrs), addrs)
ip := addrs[rand.Intn(len(addrs))]
log.Printf("%s I choose %s", r.URL.Path, ip)
url := fmt.Sprintf("http://%s:%d%s", ip, f.port, r.URL.Path)
log.Printf("%s Calling %s", r.URL.Path, url)
if err = copy(url, ip, w); err != nil {
log.Println("Error", err)
http.Error(w, err.Error(), 500)
return
}
}
func copy(url, ip string, w http.ResponseWriter) error {
resp, err := http.Get(url)
if err != nil {
return err
}
for header, values := range resp.Header {
for _, value := range values {
w.Header().Add(header, value)
}
}
w.Header().Set("source", ip)
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
_, err = w.Write(buf)
return err
}