hugo-micropub/query.go

95 lines
2.0 KiB
Go
Raw Normal View History

2019-11-14 17:46:49 +00:00
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
type ItemList struct {
Items []*MicroformatItem `json:"items"`
2019-11-14 17:46:49 +00:00
}
func QueryURL(url string, limit int) ([]byte, error) {
if len(url) == 0 {
2019-12-06 09:32:30 +00:00
url = BlogUrl
2019-11-14 17:46:49 +00:00
}
2019-12-06 09:32:30 +00:00
if url == BlogUrl {
2019-11-14 17:46:49 +00:00
allPosts, err := allPosts(url)
if err != nil {
return nil, err
}
itemList := &ItemList{}
for i, postURL := range allPosts {
if limit != 0 && i == limit {
break
}
item, _ := getItem(postURL)
itemList.Items = append(itemList.Items, item)
}
jsonBytes, err := json.Marshal(itemList)
if err != nil {
err = errors.New("failed to marshal json")
return nil, err
}
return jsonBytes, err
} else {
item, err := getItem(url)
if err != nil {
return nil, err
}
jsonBytes, err := json.Marshal(item)
if err != nil {
err = errors.New("failed to marshal json")
return nil, err
}
return jsonBytes, err
}
}
func getItem(url string) (item *MicroformatItem, err error) {
2019-11-14 17:46:49 +00:00
entry, err := ReadEntry(url)
if err != nil {
return
}
item = &MicroformatItem{
2019-11-14 17:46:49 +00:00
Type: []string{"h-entry"},
Properties: &MicroformatProperties{
2019-11-14 17:46:49 +00:00
Name: []string{entry.title},
Published: []string{entry.date},
Updated: []string{entry.lastmod},
Category: entry.tags,
Content: []string{entry.content},
Url: []string{entry.location},
},
}
return
}
func allPosts(url string) ([]string, error) {
jsonFeed := &struct {
Items []struct {
Url string `json:"url"`
} `json:"items"`
}{}
resp, err := http.Get(url + "feed.json")
if err != nil {
return nil, errors.New("failed to get json feed")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.New("failed to read json feed")
}
err = json.Unmarshal(body, &jsonFeed)
if err != nil {
return nil, errors.New("failed to parse json feed")
}
var allUrls []string
for _, item := range jsonFeed.Items {
allUrls = append(allUrls, item.Url)
}
return allUrls, nil
}