74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
|
package feed
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"github.com/gorilla/feeds"
|
||
|
"github.com/labstack/echo/v4"
|
||
|
"sh.org.ru/pkg/model"
|
||
|
)
|
||
|
|
||
|
func (h *Handler) Feed(c echo.Context) error {
|
||
|
feedType := c.Param("type")
|
||
|
|
||
|
quotes := make([]model.Quote, 0, 20)
|
||
|
err := h.db.NewSelect().
|
||
|
Model((*model.Quote)(nil)).
|
||
|
Order("id DESC").
|
||
|
Where("approved = ?", true).
|
||
|
Limit(20).
|
||
|
Scan(c.Request().Context(), "es)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
feed := &feeds.Feed{
|
||
|
Title: "sh.org.ru - Новый цитатник Рунета",
|
||
|
Link: &feeds.Link{Href: h.cfg.Host},
|
||
|
Description: "",
|
||
|
Author: &feeds.Author{Name: "NeonXP", Email: "i@neonxp.ru"},
|
||
|
Created: time.Now(),
|
||
|
}
|
||
|
|
||
|
for _, q := range quotes {
|
||
|
uid := fmt.Sprintf("%s/quote/%d", h.cfg.Host, q.ID)
|
||
|
feed.Items = append(feed.Items, &feeds.Item{
|
||
|
Id: uid,
|
||
|
Title: fmt.Sprintf("Цитата #%d", q.ID),
|
||
|
Link: &feeds.Link{Href: uid},
|
||
|
Created: q.CreatedAt,
|
||
|
Description: q.Text(),
|
||
|
})
|
||
|
}
|
||
|
switch feedType {
|
||
|
case "rss":
|
||
|
result, err := feed.ToRss()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
c.Response().Header().Set("Content-Type", "application/rss+xml")
|
||
|
return c.String(http.StatusOK, result)
|
||
|
case "atom":
|
||
|
result, err := feed.ToAtom()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
c.Response().Header().Set("Content-Type", "application/atom+xml")
|
||
|
return c.String(http.StatusOK, result)
|
||
|
case "json":
|
||
|
result, err := feed.ToJSON()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
c.Response().Header().Set("Content-Type", "application/json")
|
||
|
return c.String(http.StatusOK, result)
|
||
|
default:
|
||
|
return echo.ErrNotFound
|
||
|
}
|
||
|
}
|