Compare commits

...

2 Commits

Author SHA1 Message Date
Niko Abeler a610515d5e sitemap 2023-07-25 19:10:37 +02:00
Niko Abeler ea9059f9f0 robots.txt 2023-07-25 18:59:25 +02:00
2 changed files with 77 additions and 0 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"
@ -98,6 +102,16 @@ func NewWebApp(
app.Get("/index.xml", rssHandler.Handle)
// Posts
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(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())
}