diff options
Diffstat (limited to 'pkg/handler/feed/feed.go')
-rw-r--r-- | pkg/handler/feed/feed.go | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/pkg/handler/feed/feed.go b/pkg/handler/feed/feed.go new file mode 100644 index 0000000..05921e9 --- /dev/null +++ b/pkg/handler/feed/feed.go @@ -0,0 +1,73 @@ +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 + } +} |