forked from hverr/go-redirect
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
82 lines (66 loc) · 1.55 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
package main
import (
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
)
type Options struct {
ShowHelp bool
Source string
Destination string
}
func main() {
o := parseOptions()
handler := RedirectHandler{
Destination: o.Destination,
}
listen := fmt.Sprintf(":%s", o.Source)
fmt.Println("Listening on", listen)
log.Fatal(http.ListenAndServe(listen, handler))
}
type RedirectHandler struct {
Destination string
}
func (h RedirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.Host)
redirCode := http.StatusMovedPermanently
if err != nil {
host = r.Host
}
if r.Method != "GET" {
// RFC-7538: Redirecting non-GET requests requires a 308 instead of a 301.
// Otherwise they'll be re-transmitted as GETs, which may break some clients.
redirCode = http.StatusPermanentRedirect
}
destination := *r.URL
destination.Scheme = "https"
if h.Destination != "443" {
destination.Host = net.JoinHostPort(host, h.Destination)
} else {
destination.Host = host
}
log.Printf(
"Redirecting to %s %s\n",
r.Method, destination.String(),
)
http.Redirect(w, r, destination.String(), redirCode)
}
func parseOptions() Options {
var o Options
flag.BoolVar(&o.ShowHelp, "help", false, "show this help")
flag.StringVar(&o.Source, "port", "80", "port to listen on")
flag.StringVar(&o.Destination, "destination", "443", "port to redirect to")
flag.Parse()
printHelp := func() {
fmt.Println("redirect [options]")
flag.PrintDefaults()
}
if o.ShowHelp {
printHelp()
os.Exit(0)
}
return o
}