diff --git a/htmgo-site/internal/sitemap/generate.go b/htmgo-site/internal/sitemap/generate.go new file mode 100644 index 0000000..8a52fd6 --- /dev/null +++ b/htmgo-site/internal/sitemap/generate.go @@ -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) +} diff --git a/htmgo-site/main.go b/htmgo-site/main.go index 50b0b30..2ee2dc7 100644 --- a/htmgo-site/main.go +++ b/htmgo-site/main.go @@ -6,6 +6,7 @@ import ( "htmgo-site/__htmgo" "htmgo-site/internal/cache" "htmgo-site/internal/markdown" + "htmgo-site/internal/sitemap" "io/fs" "net/http" ) @@ -35,6 +36,16 @@ func main() { 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))) __htmgo.Register(app.Router)