forked from srcrs/rss-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
232 lines (208 loc) · 5.01 KB
/
main.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package main
import (
"embed"
"encoding/json"
"html/template"
"io/ioutil"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/mmcdole/gofeed"
)
type Config struct {
Values []string `json:"values"`
ReFresh int `json:"refresh"`
AutoUpdatePush int `json:"autoUpdatePush"`
}
var (
dbMap map[string]feed
rssUrls Config
upgrader = websocket.Upgrader{}
lock sync.RWMutex
//go:embed static
dirStatic embed.FS
//go:embed index.html
fileIndex embed.FS
htmlContent []byte
)
func init() {
// 读取配置文件
data, err := ioutil.ReadFile("config.json")
if err != nil {
panic(err)
}
// 解析JSON数据到Config结构体
err = json.Unmarshal(data, &rssUrls)
if err != nil {
panic(err)
}
// 读取 index.html 内容
htmlContent, err = fileIndex.ReadFile("index.html")
if err != nil {
panic(err)
}
dbMap = make(map[string]feed)
}
func main() {
go updateFeeds()
http.HandleFunc("/feeds", getFeedsHandler)
http.HandleFunc("/ws", wsHandler)
// http.HandleFunc("/", serveHome)
http.HandleFunc("/", tplHandler)
//加载静态文件
fs := http.FileServer(http.FS(dirStatic))
http.Handle("/static/", fs)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func serveHome(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/html; charset=utf-8")
w.Write(htmlContent)
}
func tplHandler(w http.ResponseWriter, r *http.Request) {
// 创建一个新的模板,并设置自定义分隔符为<< >>,避免与Vue的语法冲突
tmplInstance := template.New("index.html").Delims("<<", ">>")
//添加加法函数计数
funcMap := template.FuncMap{
"inc": func(i int) int {
return i + 1
},
}
// 加载模板文件
tmpl, err := tmplInstance.Funcs(funcMap).ParseFS(fileIndex, "index.html")
if err != nil {
log.Println("模板加载错误:", err)
return
}
// 定义一个数据对象
data := struct {
Keywords string
RssDataList []feed
}{
Keywords: getKeywords(),
RssDataList: getFeeds(),
}
// 渲染模板并将结果写入响应
err = tmpl.Execute(w, data)
if err != nil {
log.Println("模板渲染错误:", err)
}
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Upgrade failed: %v", err)
return
}
defer conn.Close()
for {
for _, url := range rssUrls.Values {
lock.RLock()
cache, ok := dbMap[url]
lock.RUnlock()
if !ok {
log.Printf("Error getting feed from db is null %v", url)
continue
}
data, err := json.Marshal(cache)
if err != nil {
log.Printf("json marshal failure: %s", err.Error())
continue
}
err = conn.WriteMessage(websocket.TextMessage, data)
//错误直接关闭更新
if err != nil {
log.Printf("Error sending message or Connection closed: %v", err)
return
}
}
//如果未配置则不自动更新
if rssUrls.AutoUpdatePush == 0 {
return
}
time.Sleep(time.Duration(rssUrls.AutoUpdatePush) * time.Minute)
}
}
func updateFeeds() {
var (
tick = time.Tick(time.Duration(rssUrls.ReFresh) * time.Minute)
fp = gofeed.NewParser()
)
for {
formattedTime := time.Now().Format("2006-01-02 15:04:05")
for _, url := range rssUrls.Values {
go updateFeed(fp, url, formattedTime)
}
<-tick
}
}
func updateFeed(fp *gofeed.Parser, url, formattedTime string) {
fp.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.40"
result, err := fp.ParseURL(url)
if err != nil {
log.Printf("Error fetching feed: %v | %v", url, err)
return
}
//feed内容无更新时无需更新缓存
if cache, ok := dbMap[url]; ok &&
len(result.Items) > 0 &&
len(cache.Items) > 0 &&
result.Items[0].Link == cache.Items[0].Link {
return
}
customFeed := feed{
Title: result.Title,
Link: result.Link,
Custom: map[string]string{"lastupdate": formattedTime},
Items: make([]item, 0, len(result.Items)),
}
for _, v := range result.Items {
customFeed.Items = append(customFeed.Items, item{
Link: v.Link,
Title: v.Title,
Description: v.Description,
})
}
lock.Lock()
defer lock.Unlock()
dbMap[url] = customFeed
}
// 获取feeds列表
func getFeeds() []feed {
feeds := make([]feed, 0, len(rssUrls.Values))
for _, url := range rssUrls.Values {
lock.RLock()
cache, ok := dbMap[url]
lock.RUnlock()
if !ok {
log.Printf("Error getting feed from db is null %v", url)
continue
}
feeds = append(feeds, cache)
}
return feeds
}
// 获取关键词也就是title
// 获取feeds列表
func getKeywords() string {
words := ""
for _, url := range rssUrls.Values {
lock.RLock()
cache, ok := dbMap[url]
lock.RUnlock()
if !ok {
log.Printf("Error getting feed from db is null %v", url)
continue
}
if cache.Title != "" {
words += cache.Title + ","
}
}
return words
}
func getFeedsHandler(w http.ResponseWriter, r *http.Request) {
feeds := getFeeds()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(feeds)
}