-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredirecter.go
159 lines (149 loc) · 3.49 KB
/
redirecter.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package shorturl
import (
"fmt"
"github.com/bwmarrin/snowflake"
"github.com/fsnotify/fsnotify"
"github.com/patrickmn/go-cache"
"io"
"log"
"net/http"
"net/url"
"path"
"strings"
"time"
)
func NewRedirecter(files []string, baseUrl string, strict bool, enableCache bool) (*Redirecter, error) {
bks := make(map[int64]Backend)
for _, f := range files {
bk, err := SqliteOpen(f, false, 0)
if err != nil {
return nil, err
}
nodeId, err := bk.getNodeId()
if err != nil {
return nil, err
}
if _, ok := bks[nodeId]; ok {
return nil, fmt.Errorf("duplicated nodeIds in files provided on node ID %d", nodeId)
}
bks[nodeId] = bk
}
realBaseUrl, err := url.ParseRequestURI(baseUrl)
if err != nil {
return nil, err
}
if realBaseUrl.Scheme == "" {
return nil, fmt.Errorf("baseUrl is not a full url")
}
if !strings.HasSuffix(realBaseUrl.Path, "/") {
realBaseUrl.Path += "/"
}
var urlCache *cache.Cache = nil
if enableCache {
urlCache = createCacheWithFileWatcher(files)
}
return &Redirecter{bks, realBaseUrl, strict, urlCache}, nil
}
func createCacheWithFileWatcher(files []string) *cache.Cache {
urlCache := cache.New(5*time.Minute, 10*time.Minute)
// fsnotify for urlCache clear
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Println("fsnotify init failed, just ignore.", err)
} else {
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Has(fsnotify.Write) {
urlCache.Flush() // clear cache if DB modified
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("fsnotify error:", err)
}
}
}()
for _, f := range files {
err = watcher.Add(f)
if err != nil {
log.Printf("failed on watching %v, ignored: %v", f, err)
}
}
}
return urlCache
}
func (r *Redirecter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
if r.strict && req.Host != r.baseUrl.Host {
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
reqPathDir, reqFinalSeg := path.Split(req.URL.Path)
if reqPathDir != r.baseUrl.Path {
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
if reqFinalSeg == "" {
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
if r.cache != nil {
if cachedUrl, found := r.cache.Get(reqFinalSeg); found {
if cachedUrl == nil {
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
http.Redirect(w, req, cachedUrl.(string), 302)
}
}
id, err := snowflake.ParseBase58([]byte(reqFinalSeg))
if err != nil {
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
if _, ok := r.bks[id.Node()]; !ok {
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
entry, err := r.bks[id.Node()].QueryById(uint64(id))
if err != nil {
log.Printf("failed on querying %s: %v", reqFinalSeg, err)
w.WriteHeader(500)
_, _ = io.WriteString(w, "temporarily error")
return
}
if entry == nil {
// cache
if r.cache != nil {
r.cache.Add(reqFinalSeg, nil, cache.DefaultExpiration)
}
w.WriteHeader(404)
_, _ = io.WriteString(w, "not found")
return
}
//cache
if r.cache != nil {
if !entry.ExpireAt.Valid {
r.cache.Set(reqFinalSeg, entry.Url, cache.DefaultExpiration)
} else {
r.cache.Set(reqFinalSeg, entry.Url, time.Unix(entry.ExpireAt.Int64, 0).Sub(time.Now()))
}
}
http.Redirect(w, req, entry.Url, 302)
}