GoBlog/sitemap.go

38 lines
750 B
Go
Raw Normal View History

2020-09-22 15:15:17 +00:00
package main
import (
"net/http"
"time"
2020-10-15 15:32:46 +00:00
"github.com/araddon/dateparse"
"github.com/snabb/sitemap"
2020-09-22 15:15:17 +00:00
)
2020-10-15 17:50:34 +00:00
const sitemapPath = "/sitemap.xml"
func serveSitemap(w http.ResponseWriter, r *http.Request) {
2020-10-19 18:25:30 +00:00
posts, err := getPosts(&postsRequestConfig{})
2020-10-15 17:50:34 +00:00
if err != nil {
2020-12-24 09:09:34 +00:00
serveError(w, r, err.Error(), http.StatusInternalServerError)
2020-11-22 19:30:02 +00:00
return
2020-10-15 17:50:34 +00:00
}
sm := sitemap.New()
sm.Minify = true
for _, p := range posts {
item := &sitemap.URL{
Loc: p.fullURL()}
2020-10-15 17:50:34 +00:00
var lastMod time.Time
if p.Updated != "" {
2020-12-16 19:21:35 +00:00
lastMod, _ = dateparse.ParseLocal(p.Updated)
2020-10-15 17:50:34 +00:00
}
if p.Published != "" && lastMod.IsZero() {
2020-12-16 19:21:35 +00:00
lastMod, _ = dateparse.ParseLocal(p.Published)
2020-09-22 15:15:17 +00:00
}
2020-10-15 17:50:34 +00:00
if !lastMod.IsZero() {
item.LastMod = &lastMod
2020-09-22 15:15:17 +00:00
}
2020-10-15 17:50:34 +00:00
sm.Add(item)
2020-09-22 15:15:17 +00:00
}
2020-10-15 17:50:34 +00:00
_, _ = sm.WriteTo(w)
2020-09-22 15:15:17 +00:00
}