Move sitemap code

This commit is contained in:
Jan-Lukas Else 2020-09-22 17:15:17 +02:00
parent 6e4bbc63ca
commit 9002142524
2 changed files with 35 additions and 30 deletions

View File

@ -5,14 +5,11 @@ import (
"database/sql"
"errors"
"fmt"
"github.com/araddon/dateparse"
"github.com/go-chi/chi"
"github.com/snabb/sitemap"
"github.com/vcraescu/go-paginator"
"net/http"
"reflect"
"strconv"
"time"
)
var errPostNotFound = errors.New("post not found")
@ -195,33 +192,6 @@ func serveIndex(ic *indexConfig) func(w http.ResponseWriter, r *http.Request) {
}
}
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 {
var lastMod time.Time
if p.Updated != "" {
lastMod, _ = dateparse.ParseIn(p.Updated, time.Local)
} else if p.Published != "" {
lastMod, _ = dateparse.ParseIn(p.Published, time.Local)
}
if lastMod.IsZero() {
lastMod = time.Now()
}
sm.Add(&sitemap.URL{
Loc: appConfig.Server.PublicAddress + p.Path,
LastMod: &lastMod,
})
}
_, _ = sm.WriteTo(w)
}
}
func getPost(context context.Context, path string) (*Post, error) {
posts, err := getPosts(context, &postsRequestConfig{path: path})
if err != nil {

35
sitemap.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"github.com/araddon/dateparse"
"github.com/snabb/sitemap"
"net/http"
"time"
)
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 {
var lastMod time.Time
if p.Updated != "" {
lastMod, _ = dateparse.ParseIn(p.Updated, time.Local)
} else if p.Published != "" {
lastMod, _ = dateparse.ParseIn(p.Published, time.Local)
}
if lastMod.IsZero() {
lastMod = time.Now()
}
sm.Add(&sitemap.URL{
Loc: appConfig.Server.PublicAddress + p.Path,
LastMod: &lastMod,
})
}
_, _ = sm.WriteTo(w)
}
}