reprogl

Форк
0
/
feed.go 
146 строк · 3.4 Кб
1
package handlers
2

3
import (
4
	"encoding/xml"
5
	"errors"
6
	"fmt"
7
	"net/http"
8
	"runtime"
9
	"time"
10

11
	"xelbot.com/reprogl/container"
12
	"xelbot.com/reprogl/models"
13
	"xelbot.com/reprogl/models/repositories"
14
)
15

16
func SitemapAction(app *container.Application) http.HandlerFunc {
17
	return func(w http.ResponseWriter, r *http.Request) {
18
		if container.IsCDN(r) {
19
			w.Header().Set("Content-Type", "application/xml")
20
			cacheControl(w, container.FeedTTL)
21
			w.Write([]byte(xml.Header + "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"></urlset>\n"))
22

23
			return
24
		}
25

26
		repo := repositories.ArticleRepository{DB: app.DB}
27
		articles, err := repo.GetSitemapCollection()
28
		if err != nil {
29
			app.ServerError(w, err)
30

31
			return
32
		}
33

34
		for _, location := range articles {
35
			location.URL = container.GenerateAbsoluteURL("article", "slug", location.Slug)
36
		}
37

38
		var dt1 time.Time
39
		dt1, _ = time.Parse("02 Jan 2006 15:04:05 -0700", "25 Jun 2024 22:51:33 +0300")
40
		articles = append(articles, &models.SitemapItem{
41
			URL:       container.GenerateAbsoluteURL("info-page"),
42
			UpdatedAt: models.SitemapTime(dt1),
43
			Changfreq: "monthly",
44
		})
45
		dt1, _ = time.Parse("02 Jan 2006 15:04:05 -0700", "25 Apr 2024 17:24:39 +0300")
46
		articles = append(articles, &models.SitemapItem{
47
			URL:       container.GenerateAbsoluteURL("statistics"),
48
			UpdatedAt: models.SitemapTime(dt1),
49
			Changfreq: "monthly",
50
		})
51

52
		urlSet := models.SitemapURLSet{Items: articles}
53

54
		bytes, err := xml.Marshal(urlSet)
55
		if err != nil {
56
			app.ServerError(w, err)
57

58
			return
59
		}
60

61
		w.Header().Set("Content-Type", "application/xml")
62
		cacheControl(w, container.FeedTTL)
63
		_, err = w.Write([]byte(xml.Header + `<?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>` + "\n"))
64
		if err != nil {
65
			app.ServerError(w, err)
66

67
			return
68
		}
69

70
		_, err = w.Write(bytes)
71
		if err != nil {
72
			app.ServerError(w, err)
73
		}
74
	}
75
}
76

77
func FeedAction(app *container.Application, feedType int) http.HandlerFunc {
78
	return func(w http.ResponseWriter, r *http.Request) {
79
		var feed models.FeedGeneratorInterface
80

81
		repo := repositories.ArticleRepository{DB: app.DB}
82
		articles, err := repo.GetFeedCollection()
83
		if err != nil {
84
			app.ServerError(w, err)
85

86
			return
87
		}
88

89
		for _, location := range articles {
90
			location.URL = container.GenerateAbsoluteURL("article", "slug", location.Slug)
91
		}
92

93
		switch feedType {
94
		case models.AtomFeedType:
95
			feed = models.CreateFeed(new(models.Atom), channelData(articles))
96
		case models.RssFeedType:
97
			feed = models.CreateFeed(new(models.Rss), channelData(articles))
98
		default:
99
			app.ServerError(w, errors.New("undefined feed type"))
100

101
			return
102
		}
103

104
		bytes, err := feed.AsXML()
105
		if err != nil {
106
			app.ServerError(w, err)
107

108
			return
109
		}
110

111
		w.Header().Set("Content-Type", feed.ContentType())
112
		cacheControl(w, container.FeedTTL)
113
		_, err = w.Write([]byte(xml.Header))
114
		if err != nil {
115
			app.ServerError(w, err)
116

117
			return
118
		}
119

120
		_, err = w.Write(bytes)
121
		if err != nil {
122
			app.ServerError(w, err)
123
		}
124
	}
125
}
126

127
func channelData(items models.FeedItemList) models.FeedChannelData {
128
	cfg := container.GetConfig()
129

130
	channel := models.FeedChannelData{
131
		Title:       cfg.Host,
132
		Link:        "https://" + cfg.Host + "/",
133
		Description: cfg.Host + " - последние записи",
134
		Language:    "ru-ru",
135
		Charset:     "utf-8",
136
		Author:      cfg.Author.FullName,
137
		Email:       cfg.Author.Email,
138
		Generator: fmt.Sprintf(
139
			"Reprogl/%s (%s)",
140
			container.GitRevision,
141
			runtime.Version()),
142
		FeedItems: items,
143
	}
144

145
	return channel
146
}
147

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.