-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
97 lines (79 loc) · 1.94 KB
/
handler.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
package main
import (
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/gorilla/feeds"
)
func worker(jobs <-chan url.URL, results chan<- string) {
timeout := time.Duration(5 * time.Second)
client := http.Client{
Timeout: timeout,
}
for j := range jobs {
resp, err := client.Get(j.String())
if err != nil {
results <- ""
continue
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
results <- ""
continue
}
results <- string(body)
}
}
//RSSMergeHandler configures borked handlers with timeouts and concurrency settings
func RSSMergeHandler(w http.ResponseWriter, r *http.Request) {
sourceURLs := r.URL.Query()["source"]
if sourceURLs == nil || len(sourceURLs) == 0 {
http.Error(w, "missing feed source", http.StatusBadRequest)
return
}
sourceURL, err := url.Parse(sourceURLs[0])
if err != nil {
http.Error(w, "invalid source URL", http.StatusBadRequest)
return
}
feedURLs, err := FetchList(sourceURL)
if err != nil {
http.Error(w, "failed to fetch source list", http.StatusBadRequest)
return
}
isDay := false
if len(r.URL.Query()["day"]) != 0 {
isDay = true
}
feedJobs := make(chan url.URL, len(feedURLs))
feedResults := make(chan string, len(feedURLs))
for i := 1; i <= 20; i++ {
go worker(feedJobs, feedResults)
}
for _, v := range feedURLs {
feedJobs <- v
}
close(feedJobs)
var rawFeeds []string
for i := 1; i <= len(feedURLs); i++ {
rawFeeds = append(rawFeeds, <-feedResults)
}
mergedFeed := Merge(rawFeeds)
mergedFeed.Link.Href = sourceURL.String()
if isDay {
var filteredItems []*feeds.Item
for _, v := range mergedFeed.Items {
if time.Since(v.Created) < time.Since(mergedFeed.Items[0].Created.Add(time.Hour*-24)) {
filteredItems = append(filteredItems, v)
}
}
mergedFeed.Items = filteredItems
}
rss, err := mergedFeed.ToRss()
if err != nil {
http.Error(w, "failed to build merged feed", http.StatusBadRequest)
return
}
w.Write([]byte(rss))
}