GoBlog/sitemap.go

37 lines
848 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
)
func serveSitemap() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
posts, err := getPosts(r.Context(), &postsRequestConfig{})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
sm := sitemap.New()
sm.Minify = true
for _, p := range posts {
2020-10-15 15:32:46 +00:00
item := &sitemap.URL{
Loc: appConfig.Server.PublicAddress + p.Path}
2020-09-22 15:15:17 +00:00
var lastMod time.Time
if p.Updated != "" {
lastMod, _ = dateparse.ParseIn(p.Updated, time.Local)
2020-10-15 15:32:46 +00:00
}
if p.Published != "" && lastMod.IsZero() {
2020-09-22 15:15:17 +00:00
lastMod, _ = dateparse.ParseIn(p.Published, time.Local)
}
2020-10-15 15:32:46 +00:00
if !lastMod.IsZero() {
item.LastMod = &lastMod
2020-09-22 15:15:17 +00:00
}
2020-10-15 15:32:46 +00:00
sm.Add(item)
2020-09-22 15:15:17 +00:00
}
_, _ = sm.WriteTo(w)
}
}