forked from writefreely/writefreely
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sitemap.go
109 lines (94 loc) · 2.14 KB
/
sitemap.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
/*
* Copyright © 2018-2019 A Bunch Tell LLC.
*
* This file is part of WriteFreely.
*
* WriteFreely is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, included
* in the LICENSE file in this source code package.
*/
package writefreely
import (
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/ikeikeikeike/go-sitemap-generator/v2/stm"
"github.com/writeas/web-core/log"
)
func buildSitemap(host, alias string) *stm.Sitemap {
sm := stm.NewSitemap(0)
sm.SetDefaultHost(host)
if alias != "/" {
sm.SetSitemapsPath(alias)
}
sm.Create()
// Note: Do not call `sm.Finalize()` because it flushes
// the underlying datastructure from memory to disk.
return sm
}
func handleViewSitemap(app *App, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
// Determine canonical blog URL
alias := vars["collection"]
subdomain := vars["subdomain"]
isSubdomain := subdomain != ""
if isSubdomain {
alias = subdomain
}
host := fmt.Sprintf("%s/%s/", app.cfg.App.Host, alias)
var c *Collection
var err error
pre := "/"
if app.cfg.App.SingleUser {
c, err = app.db.GetCollectionByID(1)
} else {
c, err = app.db.GetCollection(alias)
}
if err != nil {
return err
}
c.hostName = app.cfg.App.Host
if !isSubdomain {
pre += alias + "/"
}
host = c.CanonicalURL()
sm := buildSitemap(host, pre)
posts, err := app.db.GetPosts(app.cfg, c, 0, false, false, false)
if err != nil {
log.Error("Error getting posts: %v", err)
return err
}
lastSiteMod := time.Now()
for i, p := range *posts {
if i == 0 {
lastSiteMod = p.Updated
}
u := stm.URL{
{"loc", p.Slug.String},
{"changefreq", "weekly"},
{"mobile", true},
{"lastmod", p.Updated},
}
if len(p.Images) > 0 {
imgs := []stm.URL{}
for _, i := range p.Images {
imgs = append(imgs, stm.URL{
{"loc", i},
{"title", ""},
})
}
u = append(u, []interface{}{"image", imgs})
}
sm.Add(u)
}
// Add top URL
sm.Add(stm.URL{
{"loc", pre},
{"changefreq", "daily"},
{"priority", "1.0"},
{"lastmod", lastSiteMod},
})
w.Write(sm.XMLContent())
return nil
}