-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
63 lines (55 loc) · 1.44 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
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"runtime"
"strings"
)
// Version number constant.
const Version = "0.0.6"
// Homepage url.
const Homepage = "https://github.com/servian/https-echo"
var (
httpAddr = flag.String("listen", ":80", "Listen address")
destPort = flag.Int("port", -1, "Destination port")
versDisp = flag.Bool("version", false, "Display version")
)
func redirect(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Server", "Https-echo/"+Version+" (+"+Homepage+")")
if "/health" == req.URL.Path {
io.WriteString(w, "Healthy.\n")
return
}
hostname := strings.Split(req.Host, ":")
dps := ""
if *destPort > 0 {
dps = fmt.Sprintf(":%d", *destPort)
}
target := "https://" + hostname[0] + dps + req.URL.Path
if len(req.URL.RawQuery) > 0 {
target += "?" + req.URL.RawQuery
}
if xff := req.Header.Get("X-Forwarded-For"); xff != "" {
log.Printf("redirect to: %s from: %s xff %s", target, req.RemoteAddr, xff)
} else {
log.Printf("redirect to: %s from: %s", target, req.RemoteAddr)
}
http.Redirect(w, req, target, http.StatusTemporaryRedirect)
}
func main() {
flag.Parse()
if *versDisp {
fmt.Printf("Version: v%s %s\n", Version, runtime.Version())
fmt.Printf("Home Page: %s\n", Homepage)
os.Exit(0)
}
log.Printf("Listening for incoming requests on TCP port '%s'...", *httpAddr)
err := http.ListenAndServe(*httpAddr, http.HandlerFunc(redirect))
if err != nil {
log.Fatal(err)
}
}