forked from holic/redirect.name
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.go
65 lines (53 loc) · 1.22 KB
/
translate.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
package main
import (
"bytes"
"regexp"
"strings"
)
type Redirect struct {
Location string
Status int
}
func Translate(uri string, config *Config) *Redirect {
if uri == "" {
return nil
}
if config == nil {
return nil
}
if config.To == "" {
return nil
}
redirect := &Redirect{Location: config.To}
switch config.RedirectState {
case "301", "permanently":
redirect.Status = 301
case "302", "temporarily":
redirect.Status = 302
case "307":
redirect.Status = 307
case "308":
redirect.Status = 308
default:
redirect.Status = 302
}
// no `From` assumes catch-all, so redirect immediately to `Location`
if config.From == "" {
return redirect
}
count := strings.Count(config.From, `*`)
var exp bytes.Buffer
exp.WriteString(`^`)
exp.WriteString(strings.Replace(regexp.QuoteMeta(config.From), `\*`, `(.*)`, 1))
exp.WriteString(`$`)
fromRE := regexp.MustCompile(exp.String())
// if we can't find the pattern, return to continue to next record
if !fromRE.MatchString(uri) {
return nil
}
// wildcard replacement of `uri` if there's a wildcard in our `From` path
if count > 0 {
redirect.Location = fromRE.ReplaceAllString(uri, strings.Replace(redirect.Location, `*`, `${1}`, 1))
}
return redirect
}