forked from silinternational/domain-redirector-landing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
95 lines (81 loc) · 1.91 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
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"strconv"
)
var (
additionalMessage template.HTML
newHost string
moreInfoURL string
port string
redirectEndDate string
skipLandingPage bool
)
type pageData struct {
OldHost string
NewHost string
NewURL string
MoreInfoURL string
RedirectEndDate string
AdditionalMessage template.HTML
}
func loadConfig() {
newHost = os.Getenv("NEW_HOST")
if newHost == "" {
log.Println("NEW_HOST env var is required")
os.Exit(1)
}
port = os.Getenv("PORT")
if port == "" {
port = "80"
}
// optional vars
moreInfoURL = os.Getenv("MORE_INFO_URL")
redirectEndDate = os.Getenv("REDIRECT_END_DATE")
additionalMessage = template.HTML(os.Getenv("ADDITIONAL_MESSAGE"))
skipLandingPage, _ = strconv.ParseBool(os.Getenv("SKIP_LANDING_PAGE"))
}
func main() {
loadConfig()
http.HandleFunc("/", serveTemplate)
err := http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
if err != nil {
log.Fatal(err)
}
}
func serveTemplate(w http.ResponseWriter, r *http.Request) {
data := getPageData(r)
if skipLandingPage {
w.Header().Set("Location", data.NewURL)
w.WriteHeader(http.StatusMovedPermanently)
return
}
tmpl, err := template.New("index").Parse(pageTemplate)
if err != nil {
log.Println(err.Error())
http.Error(w, http.StatusText(500), 500)
return
}
if err := tmpl.Execute(w, data); err != nil {
log.Println(err.Error())
http.Error(w, http.StatusText(500), 500)
}
}
func getPageData(r *http.Request) pageData {
query := ""
if len(r.URL.Query()) > 0 {
query = "?" + r.URL.Query().Encode()
}
return pageData{
OldHost: r.Host,
NewHost: newHost,
NewURL: fmt.Sprintf("https://%s%s%s", newHost, r.URL.Path, query),
MoreInfoURL: moreInfoURL,
RedirectEndDate: redirectEndDate,
AdditionalMessage: additionalMessage,
}
}