add more urls to sitemap

This commit is contained in:
maddalax 2024-10-31 18:10:11 -05:00
parent 9643e08232
commit e067a17f53
2 changed files with 24 additions and 3 deletions

View file

@ -4,6 +4,8 @@ import (
"bytes" "bytes"
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"github.com/go-chi/chi/v5"
"strings"
) )
type URL struct { type URL struct {
@ -35,8 +37,8 @@ func serialize(sitemap *URLSet) ([]byte, error) {
return buffer.Bytes(), nil return buffer.Bytes(), nil
} }
func Generate() ([]byte, error) { func Generate(router *chi.Mux) ([]byte, error) {
routes := router.Routes()
urls := []URL{ urls := []URL{
{ {
Loc: "/", Loc: "/",
@ -59,6 +61,25 @@ func Generate() ([]byte, error) {
ChangeFreq: "weekly", ChangeFreq: "weekly",
}, },
} }
for _, route := range routes {
if strings.HasPrefix(route.Pattern, "/docs/") {
urls = append(urls, URL{
Loc: route.Pattern,
Priority: 1.0,
ChangeFreq: "weekly",
})
}
if strings.HasPrefix(route.Pattern, "/examples/") {
urls = append(urls, URL{
Loc: route.Pattern,
Priority: 0.7,
ChangeFreq: "weekly",
})
}
}
sitemap := NewSitemap(urls) sitemap := NewSitemap(urls)
return serialize(sitemap) return serialize(sitemap)
} }

View file

@ -37,7 +37,7 @@ func main() {
http.FileServerFS(sub) http.FileServerFS(sub)
app.Router.Handle("/sitemap.xml", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { app.Router.Handle("/sitemap.xml", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, err := sitemap.Generate() s, err := sitemap.Generate(app.Router)
if err != nil { if err != nil {
http.Error(w, "failed to generate sitemap", http.StatusInternalServerError) http.Error(w, "failed to generate sitemap", http.StatusInternalServerError)
return return