-
Notifications
You must be signed in to change notification settings - Fork 11
/
loadbalancer.go
87 lines (68 loc) · 1.9 KB
/
loadbalancer.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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"time"
)
// LoadbalancerResponse represents a response from the loadbalancer
type LoadbalancerResponse struct {
Redirect string `json:"redirect"`
ClientIP string `json:"client_ip"`
CountryCode string `json:"country_code"`
Timestamp int64 `json:"timestamp"`
}
// Loadbalancer responds to a request to the loadbalancer
func Loadbalancer(w http.ResponseWriter, req *http.Request) {
// Set some headers
w.Header().Set("Connection", "close")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Server", "go-streaming-loadbalancer")
// Connect to Redis
c := pool.Get()
if c.Err() != nil {
log.Print("Error: ", c.Err())
w.Header().Set("Content-Type", "text/plain")
http.Error(w, "Could not connect to Redis server", 503)
return
}
// Make sure that the Redis connection is closed
defer c.Close()
// Retrieve the redirect ip
redirectIP, err := getRedirectIP(c)
if err != nil {
log.Print("Error: ", err)
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
cc := ""
loc := gi.GetLocationByIP(host)
if loc != nil {
cc = loc.CountryCode
}
// Populate the loadbalancer response struct
response := LoadbalancerResponse{
Redirect: redirectIP,
Timestamp: time.Now().Unix(),
CountryCode: cc,
ClientIP: host,
}
// Marshal the JSON
json, err := json.Marshal(response)
if err != nil {
fmt.Println("JSON Error:", err)
}
callback := req.FormValue("callback")
if callback == "" {
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(json)))
// Return the JSON to the client
w.Write(json)
} else {
contentLength := fmt.Sprintf("%d", len(json)+len(callback)+2)
w.Header().Set("Content-Type", "application/javascript")
w.Header().Set("Content-Length", contentLength)
w.Write([]byte(fmt.Sprintf("%s(%s)", callback, json)))
}
}