/
main.go
83 lines (72 loc) · 1.85 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
package main
import (
"fmt"
"log"
"net"
"net/http"
"os"
"strconv"
"time"
)
func launchServer(port int) {
helloHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("hello"))
})
internalAddressString := os.Getenv("CF_INSTANCE_INTERNAL_IP")
internalAddress := net.ParseIP(internalAddressString)
if internalAddress == nil {
log.Fatal("invalid required env var CF_INSTANCE_INTERNAL_IP")
}
proxyURL := os.Getenv("PROXY_APP_URL")
if proxyURL == "" {
log.Fatal("invalid required env var PROXY_APP_URL")
}
selfProxyHandler := &SelfProxyHandler{
SelfAddress: internalAddress.String(),
ProxyURL: proxyURL,
}
mux := http.NewServeMux()
mux.Handle("/selfproxy", selfProxyHandler)
mux.Handle("/", helloHandler)
http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), mux)
}
func main() {
systemPortString := os.Getenv("PORT")
systemPort, err := strconv.Atoi(systemPortString)
if err != nil {
log.Fatal("invalid required env var PORT")
}
launchServer(systemPort)
}
type SelfProxyHandler struct {
SelfAddress string
ProxyURL string
}
var httpClient = &http.Client{
Transport: &http.Transport{
DisableKeepAlives: true,
Dial: (&net.Dialer{
Timeout: 4 * time.Second,
KeepAlive: 0,
}).Dial,
},
}
func (h *SelfProxyHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
newURL := fmt.Sprintf("%s/proxy/%s:8080", h.ProxyURL, h.SelfAddress)
getResp, err := httpClient.Get(newURL)
if err != nil {
fmt.Fprintf(os.Stderr, "request failed: %s", err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(fmt.Sprintf("request failed: %s", err)))
return
}
defer getResp.Body.Close()
resp.WriteHeader(getResp.StatusCode)
switch getResp.StatusCode {
case http.StatusOK:
resp.Write([]byte("OK"))
default:
resp.Write([]byte("FAILED"))
}
}