95 lines
2.0 KiB
Go
95 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io/ioutil"
|
|
"net/http"
|
|
)
|
|
|
|
type ItemList struct {
|
|
Items []*MicroformatItem `json:"items"`
|
|
}
|
|
|
|
func QueryURL(url string, limit int) ([]byte, error) {
|
|
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 *MicroformatItem, err error) {
|
|
entry, err := ReadEntry(url)
|
|
if err != nil {
|
|
return
|
|
}
|
|
item = &MicroformatItem{
|
|
Type: []string{"h-entry"},
|
|
Properties: &MicroformatProperties{
|
|
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
|
|
}
|