This commit is contained in:
Niko Abeler 2023-07-25 19:05:55 +02:00
parent ea9059f9f0
commit a610515d5e
2 changed files with 73 additions and 1 deletions

View File

@ -2,9 +2,13 @@ package web
import (
"embed"
"fmt"
"net/http"
"net/url"
"owl-blogs/app"
"owl-blogs/app/repository"
"owl-blogs/config"
"owl-blogs/domain/model"
"owl-blogs/web/middleware"
"github.com/gofiber/fiber/v2"
@ -100,9 +104,14 @@ func NewWebApp(
app.Get("/posts/:post/", entryHandler.Handle)
// robots.txt
app.Get("/robots.txt", func(c *fiber.Ctx) error {
siteConfig := model.SiteConfig{}
configRepo.Get(config.SITE_CONFIG, &siteConfig)
sitemapUrl, _ := url.JoinPath(siteConfig.FullUrl, "/sitemap.xml")
c.Set("Content-Type", "text/plain")
return c.SendString("User-agent: *\nAllow: /\n")
return c.SendString(fmt.Sprintf("User-agent: *\nAllow: /\n\nSitemap: %s\n", sitemapUrl))
})
// sitemap.xml
app.Get("/sitemap.xml", NewSiteMapHandler(entryService, configRepo).Handle)
// ActivityPub
// activityPubServer := NewActivityPubServer(configRepo)

63
web/sitemap_handler.go Normal file
View File

@ -0,0 +1,63 @@
package web
import (
"bytes"
"encoding/xml"
"net/url"
"owl-blogs/app"
"owl-blogs/app/repository"
"github.com/gofiber/fiber/v2"
)
type SiteMapHandler struct {
entryService *app.EntryService
configRepo repository.ConfigRepository
}
type Sitemap struct {
XMLName xml.Name `xml:"urlset"`
Xmlns string `xml:"xmlns,attr"`
Url []SitemapUrl `xml:"url"`
}
type SitemapUrl struct {
Loc string `xml:"loc"`
}
func NewSiteMapHandler(entryService *app.EntryService, configRepo repository.ConfigRepository) *SiteMapHandler {
return &SiteMapHandler{entryService: entryService, configRepo: configRepo}
}
// Handle handles GET /sitemap.xml
func (h *SiteMapHandler) Handle(c *fiber.Ctx) error {
c.Set(fiber.HeaderContentType, fiber.MIMEApplicationXML)
siteConfig := getSiteConfig(h.configRepo)
entries, err := h.entryService.FindAllByType(nil, true, false)
if err != nil {
return err
}
sitemap := Sitemap{
Xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9",
Url: make([]SitemapUrl, 0),
}
for _, entry := range entries {
entryUrl, _ := url.JoinPath(siteConfig.FullUrl, "/posts/", url.PathEscape(entry.ID()), "/")
sitemap.Url = append(sitemap.Url, SitemapUrl{
Loc: entryUrl,
})
}
buf := new(bytes.Buffer)
encoder := xml.NewEncoder(buf)
encoder.Indent("", " ")
err = encoder.Encode(sitemap)
if err != nil {
return err
}
return c.SendString(xml.Header + buf.String())
}