Support XML and Atom responses

This commit is contained in:
blankie 2022-07-19 20:48:50 +07:00
parent 5cedea4836
commit f3333ab888
Signed by: blankie
GPG Key ID: CC15FC822C7F61F5
1 changed files with 53 additions and 43 deletions

96
main.go
View File

@ -6,6 +6,7 @@ import (
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"net/url"
"os"
@ -19,6 +20,7 @@ import (
)
const TIMEOUT_NS time.Duration = time.Duration(60_000_000_000)
var (
hosts tofu.KnownHosts
hostsfile *tofu.HostWriter
@ -158,52 +160,60 @@ func main() {
}
defer resp.Body.Close()
if resp.Meta != "text/gemini" && !strings.HasPrefix(resp.Meta, "text/gemini;") {
log.Fatal("mime type is not text/gemini")
}
aw := AtomWriter{
Title: "",
Items: nil,
}
gemini.ParseLines(resp.Body, aw.Handle)
sort.Sort(ByTime(aw.Items))
feed := Feed{
XMLNS: "http://www.w3.org/2005/Atom",
Link: FeedLink{
Href: req.URL.String(),
},
Id: req.URL.String(),
Entries: nil,
}
if aw.Title == "" {
feed.Title = req.URL.String()
} else {
feed.Title = aw.Title
}
if len(aw.Items) == 0 {
feed.Updated = time.Now().Format(time.RFC3339)
} else {
feed.Updated = aw.Items[len(aw.Items)-1].Date.Format(time.RFC3339)
}
for i := len(aw.Items); i != 0; i-- {
item := aw.Items[i-1]
link, err := req.URL.Parse(item.Link)
mime, _, _ := strings.Cut(resp.Meta, ";")
if mime == "application/rss+xml" || mime == "application/atom+xml" {
out, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
feed.Entries = append(feed.Entries, FeedEntry{
Title: item.Title,
Link: EntryLink{
Href: link.String(),
Rel: "alternate",
fmt.Print(string(out))
} else if mime == "text/gemini" {
aw := AtomWriter{
Title: "",
Items: nil,
}
gemini.ParseLines(resp.Body, aw.Handle)
sort.Sort(ByTime(aw.Items))
feed := Feed{
XMLNS: "http://www.w3.org/2005/Atom",
Link: FeedLink{
Href: req.URL.String(),
},
Id: link.String(),
Updated: item.Date.Format(time.RFC3339),
})
Id: req.URL.String(),
Entries: nil,
}
if aw.Title == "" {
feed.Title = req.URL.String()
} else {
feed.Title = aw.Title
}
if len(aw.Items) == 0 {
feed.Updated = time.Now().Format(time.RFC3339)
} else {
feed.Updated = aw.Items[len(aw.Items)-1].Date.Format(time.RFC3339)
}
for i := len(aw.Items); i != 0; i-- {
item := aw.Items[i-1]
link, err := req.URL.Parse(item.Link)
if err != nil {
log.Fatal(err)
}
feed.Entries = append(feed.Entries, FeedEntry{
Title: item.Title,
Link: EntryLink{
Href: link.String(),
Rel: "alternate",
},
Id: link.String(),
Updated: item.Date.Format(time.RFC3339),
})
}
out, err := xml.MarshalIndent(feed, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
} else {
log.Fatal("unsupported mime type: ", mime)
}
out, err := xml.MarshalIndent(feed, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
}