hugo-micropub/query.go

113 lines
2.3 KiB
Go

package main
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
type ItemList struct {
Items []*Item `json:"items"`
}
type Item struct {
Type []string `json:"type"`
Properties *Properties `json:"properties"`
}
type Properties struct {
Name []string `json:"name"`
Published []string `json:"published"`
Updated []string `json:"updated"`
Category []string `json:"category"`
Content []string `json:"content"`
Url []string `json:"url"`
}
func QueryURL(url string, limit int) ([]byte, error) {
blogURL, err := GetBlogURL()
if err != nil {
return nil, err
}
if len(url) == 0 {
url = blogURL
}
if url == blogURL {
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 *Item, err error) {
entry, err := ReadEntry(url)
if err != nil {
return
}
item = &Item{
Type: []string{"h-entry"},
Properties: &Properties{
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
}