add quick sitemap

This commit is contained in:
maddalax 2024-10-15 11:15:47 -05:00
parent a466726b70
commit 907cf86f6a
2 changed files with 75 additions and 0 deletions

View file

@ -0,0 +1,64 @@
package sitemap
import (
"bytes"
"encoding/xml"
"fmt"
)
type URL struct {
Loc string `xml:"loc"`
ChangeFreq string `xml:"changefreq,omitempty"`
Priority float32 `xml:"priority,omitempty"`
}
type URLSet struct {
XMLName xml.Name `xml:"urlset"`
XmlNS string `xml:"xmlns,attr"`
URLs []URL `xml:"url"`
}
func NewSitemap(urls []URL) *URLSet {
return &URLSet{
XmlNS: "https://www.sitemaps.org/schemas/sitemap/0.9",
URLs: urls,
}
}
func serialize(sitemap *URLSet) ([]byte, error) {
buffer := bytes.Buffer{}
enc := xml.NewEncoder(&buffer)
enc.Indent("", " ")
if err := enc.Encode(sitemap); err != nil {
return make([]byte, 0), fmt.Errorf("could not encode sitemap: %w", err)
}
return buffer.Bytes(), nil
}
func Generate() ([]byte, error) {
urls := []URL{
{
Loc: "/",
Priority: 0.5,
ChangeFreq: "weekly",
},
{
Loc: "/docs",
Priority: 1.0,
ChangeFreq: "daily",
},
{
Loc: "/examples",
Priority: 0.7,
ChangeFreq: "daily",
},
{
Loc: "/html-to-go",
Priority: 0.5,
ChangeFreq: "weekly",
},
}
sitemap := NewSitemap(urls)
return serialize(sitemap)
}

View file

@ -6,6 +6,7 @@ import (
"htmgo-site/__htmgo" "htmgo-site/__htmgo"
"htmgo-site/internal/cache" "htmgo-site/internal/cache"
"htmgo-site/internal/markdown" "htmgo-site/internal/markdown"
"htmgo-site/internal/sitemap"
"io/fs" "io/fs"
"net/http" "net/http"
) )
@ -35,6 +36,16 @@ func main() {
http.FileServerFS(sub) http.FileServerFS(sub)
app.Router.Handle("/sitemap.xml", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, err := sitemap.Generate()
if err != nil {
http.Error(w, "failed to generate sitemap", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/xml")
w.Write(s)
}))
app.Router.Handle("/public/*", http.StripPrefix("/public", http.FileServerFS(sub))) app.Router.Handle("/public/*", http.StripPrefix("/public", http.FileServerFS(sub)))
__htmgo.Register(app.Router) __htmgo.Register(app.Router)