-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (105 loc) · 2.61 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/julienschmidt/httprouter"
)
var (
redirectCode = http.StatusFound
redirects = make(map[string]string)
port = "8080"
bufferSize = 100000
logs chan *http.Request
disableCH = false
)
var methods = [...]string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
}
func getKey(uri string, noSearch bool) string {
path := strings.Split(uri, "*")
params := strings.Split(path[0], "?")
if _, ok := redirects[params[0]]; noSearch || ok {
return params[0]
} else {
//Find most nearest key by largest key length
var nearestKeys string
var maxKeyLen int
for key := range redirects {
if strings.Contains(params[0], key) && len(key) > maxKeyLen {
maxKeyLen = len(key)
nearestKeys = key
}
}
return nearestKeys
}
}
func generateAnswer(r *http.Request) string {
target := redirects[getKey(r.RequestURI, false)]
target = strings.Replace(target, "{URI}", r.RequestURI, -1)
return strings.Replace(target, "{HOST}", r.Host, -1)
}
func redirect(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
http.Redirect(w, r, generateAnswer(r), redirectCode)
if !disableCH {
logs <- r
}
}
func load(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprintf(w, "%d", len(logs))
}
func main() {
if portEnv, present := os.LookupEnv("PORT"); present {
if v, err := strconv.Atoi(portEnv); err == nil {
if v > 0 && v < 65536 {
port = portEnv
}
}
}
if bufferSizeEnv, present := os.LookupEnv("BUFFER"); present {
if v, err := strconv.Atoi(bufferSizeEnv); err == nil {
if v > 0 {
bufferSize = v
}
}
}
if v, present := os.LookupEnv("DISABLE_CH"); present && v == "true" {
disableCH = true
}
logs = make(chan *http.Request, bufferSize)
if !disableCH {
go logger(logs)
}
router := httprouter.New()
router.GET("/load", load)
if v, present := os.LookupEnv("PERMANENTLY"); present && v == "true" {
redirectCode = http.StatusMovedPermanently
}
if redirectsEnv, present := os.LookupEnv("REDIRECTS"); present {
entries := strings.Split(redirectsEnv, "|")
for _, entry := range entries {
kv := strings.Split(entry, " ")
if len(kv) == 2 {
redirects[getKey(kv[0], true)] = kv[1]
for _, method := range methods {
router.Handle(method, kv[0], redirect)
log.Println("Registred " + method + " " + kv[0])
}
} else {
log.Fatal("Failded to parse: " + entry)
}
}
}
log.Fatal(http.ListenAndServe(":"+port, router))
}