aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/feed/feed.go
blob: 05921e99d4a4e7f2bd4087068dd7a7741e5fb8e5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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(), &quotes)
	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
	}
}