/
redirects.go
82 lines (69 loc) · 1.88 KB
/
redirects.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
package gosling
import (
"encoding/json"
"fmt"
"html/template"
"io"
"os"
"path"
)
const defaultTemplate = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Redirecting to {{ .RedirectURL }}</title>
<link rel="canonical" href="{{ .RedirectURL }}">
<meta http-equiv="refresh" content="0; url={{ .RedirectURL }}">
<meta name="robots" content="noindex,follow">
</head>
<body>
<a href="{{ .RedirectURL }}" alt="{{ .RedirectURL }}">Click here if you are not redirected.</a>
</body>
</html>`
type templateData struct {
RedirectURL string
}
// Redirects holds redirects
type Redirects map[string]string
// NewRedirects parses redirects from a JSON files
func NewRedirects(inpath string) (Redirects, error) {
jsonFile, err := os.Open(inpath)
if err != nil {
return nil, err
}
defer jsonFile.Close()
var redir Redirects
if err := json.NewDecoder(jsonFile).Decode(&redir); err != nil {
return nil, err
}
return redir, nil
}
// BuildRedirects builds redirects to provided folder
func BuildRedirects(redir Redirects, inpath string) error {
for from, to := range redir {
dstDir := path.Clean(path.Join(inpath, from))
if err := os.MkdirAll(dstDir, 0777); err != nil {
return fmt.Errorf("unable to create a destination folder %s: %s", dstDir, err)
}
dstFile := path.Join(dstDir, "index.html")
f, err := os.Create(dstFile)
if err != nil {
return fmt.Errorf("unable to create a destination file %s: %s", dstFile, err)
}
if err := BuildRedirect(to, f); err != nil {
return fmt.Errorf("unable to build a redirect for %s: %s", to, err)
}
}
return nil
}
// BuildRedirect builds a redirect to a destination writer
func BuildRedirect(link string, wr io.Writer) error {
data := templateData{
RedirectURL: link,
}
tmpl, err := template.New("redirect").Parse(defaultTemplate)
if err != nil {
return err
}
return tmpl.Execute(wr, &data)
}