rss/main.go
2023-04-14 02:03:56 +08:00

95 lines
2.2 KiB
Go

package main
import (
"io"
"log"
"net/http"
"os"
"regexp"
"rss/bbclearn"
"strings"
"time"
)
var zhihuReg = regexp.MustCompile(`(?is:(<item>(.*?)</item>))`)
var date = regexp.MustCompile(`<pubDate>(.*)</pubDate>`)
func fetch(u string, fn ...func(s string) string) string {
res, err := http.Get(u)
if err != nil {
return ""
}
s, err := io.ReadAll(res.Body)
if err != nil {
return ""
}
html := string(s)
for _, f := range fn {
html = f(html)
}
return html
}
func dayLimit(today, forwardDay int, s string) string {
da := date.FindStringSubmatch(s)
if len(da) <= 1 {
return s
}
t, err := time.Parse(time.RFC1123Z, da[1])
if err != nil {
return s
}
if today-forwardDay > t.Day() {
return ""
}
return s
}
func filterItem(html string, today, recentDay int) string {
return zhihuReg.ReplaceAllStringFunc(html, func(s string) string {
return dayLimit(today, recentDay, s)
})
}
func penti(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, fetch("https://feedx.best/rss/pentitugua.xml", func(s string) string {
return strings.ReplaceAll(s, "www.dapenti.com:99", "imgc.1see.org")
}))
}
func zhihuDaily(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, fetch("https://feedx.best/rss/zhihudaily.xml", func(s string) string {
return filterItem(s, time.Now().Day(), 1)
}))
}
func tjxz(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, fetch("https://feedx.best/rss/tjxz.xml", func(s string) string {
return filterItem(s, time.Now().Day(), 0)
}))
}
func bbcLearn(w http.ResponseWriter, _ *http.Request) {
io.WriteString(w, fetch("https://www.bbc.co.uk/learningenglish/chinese", func(s string) string {
return bbclearn.LearnParse(s, 1)
}))
}
func theNewYorker(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, fetch("https://feedx.best/rss/newyorker.xml", func(s string) string {
return filterItem(s, time.Now().Day(), 1)
}))
}
func main() {
port := os.Getenv("port")
if port == "" {
port = ":80"
}
http.HandleFunc("/pentitugua", penti)
http.HandleFunc("/zhihuDaily", zhihuDaily)
http.HandleFunc("/tjxz", tjxz)
http.HandleFunc("/bbcLearn", bbcLearn)
http.HandleFunc("/theNewYorker", theNewYorker)
log.Fatal(http.ListenAndServe(port, nil))
}