-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (56 loc) · 1.62 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
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
)
// Get env var or default
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
// Given a request send it to the appropriate url
func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {
// parse the url
url, _ := url.Parse(getEnv("RF_FORWARD_URL", "https://api.ipgeolocation.io"))
debug, _ := strconv.ParseBool(getEnv("RF_DEBUG", "false"))
// create the reverse proxy
proxy := httputil.NewSingleHostReverseProxy(url)
// Update the headers to allow for SSL redirection
req.URL.Host = url.Host
req.URL.Scheme = url.Scheme
req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
req.Host = url.Host
// We need to clear the remote addr field so the getip endpoint works properly
originalRemoteAddr := req.RemoteAddr
req.RemoteAddr = ""
if debug {
log.Println(":::START:Forwarding Request:::")
log.Printf("URI: %s\n", req.URL)
log.Printf("Host: %s\n", req.URL.Host)
log.Printf("Path: %s\n", req.URL.Path)
log.Printf("URI: %s\n", req.URL.RequestURI())
log.Printf("Body: %s\n", req.Body)
log.Printf("originalRemoteAddr: %s\n", originalRemoteAddr)
log.Printf("FullRequest: %s\n", req)
log.Println(":::END:Forwarding Request:::")
}
// Note that ServeHttp is non blocking and uses a go routine under the hood
proxy.ServeHTTP(res, req)
}
/*
Entry
*/
func main() {
port := getEnv("RF_PORT", "8080")
// start server
http.HandleFunc("/", handleRequestAndRedirect)
if err := http.ListenAndServe(":"+port, nil); err != nil {
panic(err)
}
}