-
Notifications
You must be signed in to change notification settings - Fork 35
/
server.go
85 lines (74 loc) · 1.67 KB
/
server.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
package main
import (
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
func fallback(w http.ResponseWriter, r *http.Request, reason string) {
location := os.Getenv("FALLBACK_URL")
if location == "" {
location = "http://redirect.name/"
}
if reason != "" {
location = fmt.Sprintf("%s#reason=%s", location, url.QueryEscape(reason))
}
http.Redirect(w, r, location, 302)
}
func getRedirect(txt []string, url string) (*Redirect, error) {
var catchAlls []*Config
for _, record := range txt {
config := Parse(record)
if config.From == "" {
catchAlls = append(catchAlls, config)
continue
}
redirect := Translate(url, config)
if redirect != nil {
return redirect, nil
}
}
var config *Config
for _, config = range catchAlls {
redirect := Translate(url, config)
if redirect != nil {
return redirect, nil
}
}
return nil, errors.New("No paths matched")
}
func handler(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.Host, ":")
host := parts[0]
hostname := fmt.Sprintf("_redirect.%s", host)
txt, err := net.LookupTXT(hostname)
if err != nil {
fallback(w, r, fmt.Sprintf("Could not resolve hostname (%v)", err))
return
}
redirect, err := getRedirect(txt, r.URL.String())
if err != nil {
fallback(w, r, err.Error())
} else {
http.Redirect(w, r, redirect.Location, redirect.Status)
}
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8081"
}
http.HandleFunc("/", handler)
srv := &http.Server{
Addr: ":" + port,
ReadTimeout: 2 * time.Second,
WriteTimeout: 2 * time.Second,
}
log.Printf("Listening on http://127.0.0.1:%s", port)
log.Fatal(srv.ListenAndServe())
}