-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsitemap_generator.go
56 lines (44 loc) · 1.01 KB
/
sitemap_generator.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
package andrew
import (
"bytes"
"fmt"
"io/fs"
"net/http"
"path/filepath"
"strings"
)
// SiteMap
func (a Server) ServeSiteMap(w http.ResponseWriter, r *http.Request) {
sitemap := GenerateSiteMap(a.SiteFiles, a.BaseUrl)
w.WriteHeader(http.StatusOK)
_, err := fmt.Fprint(w, string(sitemap))
if err != nil {
panic(err)
}
}
// Generates and returns a sitemap.xml.
func GenerateSiteMap(f fs.FS, baseUrl string) []byte {
buff := new(bytes.Buffer)
const (
header = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
`
footer = `</urlset>
`
)
fmt.Fprint(buff, header)
fs.WalkDir(f, ".", func(path string, dir fs.DirEntry, err error) error {
if err != nil {
return err
}
if filepath.Ext(path) == ".html" {
// index.html
// foo/bar/index.html
path = strings.TrimSuffix(path, "index.html")
fmt.Fprintf(buff, "\t<url>\n\t\t<loc>%s/%s</loc>\n\t</url>\n", baseUrl, path)
}
return nil
})
fmt.Fprint(buff, footer)
return buff.Bytes()
}