rss/main.go
2023-07-11 12:28:38 +08:00

114 lines
2.9 KiB
Go

package main
import (
str "github.com/fthvgb1/wp-go/helper/strings"
"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 ""
}
defer res.Body.Close()
html := string(s)
for _, f := range fn {
html = f(html)
}
return html
}
func dayLimit(now time.Time, forwardDay int, s, format string) string {
da := date.FindStringSubmatch(s)
if len(da) <= 1 {
return s
}
t, err := time.Parse(format, da[1])
if err != nil {
return s
}
day := now.Sub(t).Hours() / 24
if day-float64(forwardDay) > 0 {
return ""
}
return s
}
func filterItem(html string, now time.Time, recentDay int) string {
return zhihuReg.ReplaceAllStringFunc(html, func(s string) string {
return dayLimit(now, recentDay, s, time.RFC1123Z)
})
}
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(), recentDay)
}))
}
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(), recentDay)
}))
}
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, recentDay)
}))
}
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(), recentDay)
}))
}
func voaLearnEnglish(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, fetch("https://feedx.best/rss/voalearningenglish.xml", func(s string) string {
return filterItem(s, time.Now(), recentDay)
}))
}
var recentDay = 1
func main() {
port := os.Getenv("port")
if port == "" {
port = ":80"
}
day := os.Getenv("rss_recent_day")
if day != "" {
recentDay = str.ToInt[int](day)
}
time.Local = time.FixedZone("CST", 3600*8)
http.HandleFunc("/pentitugua", penti) //喷嚏图挂
http.HandleFunc("/zhihuDaily", zhihuDaily) //知乎日报
http.HandleFunc("/tjxz", tjxz) //田间小站
http.HandleFunc("/bbcLearn", bbcLearn) //bbc 英语学习
http.HandleFunc("/theNewYorker", theNewYorker) //纽约客
http.HandleFunc("/voaLearnEnglish", voaLearnEnglish) //VOA Learning English
log.Fatal(http.ListenAndServe(port, nil))
}