-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
107 lines (92 loc) · 2.52 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
107
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
)
const keyServerAddr = "serverAddr"
func handle(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
s := ctx.Value(keyServerAddr)
fmt.Fprintf(w, "Hello from %s! This is a carbon-aware server response\n", s)
}
func createBackendServer(ctx context.Context, port string, mux *http.ServeMux) *http.Server {
return &http.Server{
Addr: ":" + port,
Handler: mux,
BaseContext: func(l net.Listener) context.Context {
ctx = context.WithValue(ctx, keyServerAddr, l.Addr().String())
return ctx
},
}
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", handle)
ctx, cancelCtx := context.WithCancel(context.Background())
irelandEast := createBackendServer(ctx, "3333", mux)
irelandWest := createBackendServer(ctx, "3334", mux)
london := createBackendServer(ctx, "4444", mux)
paris := createBackendServer(ctx, "5555", mux)
go func() {
err := irelandEast.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("irelandEast closed\n")
} else if err != nil {
fmt.Printf("error listening for irelandEast: %s\n", err)
}
cancelCtx()
}()
go func() {
err := irelandWest.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("irelandWest closed\n")
} else if err != nil {
fmt.Printf("error listening for irelandWest: %s\n", err)
}
cancelCtx()
}()
go func() {
err := london.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("london closed\n")
} else if err != nil {
fmt.Printf("error listening for london: %s\n", err)
}
cancelCtx()
}()
go func() {
err := paris.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("paris closed\n")
} else if err != nil {
fmt.Printf("error listening for paris three: %s\n", err)
}
cancelCtx()
}()
irelandServers := []server{
CreateBackend("http://localhost:3333"),
CreateBackend("http://localhost:3334"),
}
parisServers := []server{
CreateBackend("http://localhost:4444"),
}
londonServers := []server{
CreateBackend("http://localhost:5555"),
}
regions := []*region{
CreateRegion(irelandServers, 0, "eu-west-1"),
CreateRegion(parisServers, 0, "eu-west-2"),
CreateRegion(londonServers, 0, "eu-west-3"),
}
lb := NewLoadBalancer(regions)
handler := func(rw http.ResponseWriter, r *http.Request) {
lb.HandleRequest(rw, r)
}
http.HandleFunc("/", handler)
fmt.Printf("carlo load balancer listening at 'localhost:%s'\n", "8000")
http.ListenAndServe(":"+"8000", nil)
<-ctx.Done()
}