catbase/plugins/newsbid/webshit/hn/api.go

44 lines
753 B
Go
Raw Normal View History

2019-11-21 16:59:52 +00:00
package hn
import (
"encoding/json"
"fmt"
"net/http"
)
2019-11-22 16:51:48 +00:00
const BASE = `https://hacker-news.firebaseio.com/v0`
2019-11-21 16:59:52 +00:00
func get(url string) (*http.Response, error) {
c := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("User-Agent", "catbase/1.0")
return c.Do(req)
}
func GetItem(id int) (Item, error) {
2019-11-22 16:51:48 +00:00
u := fmt.Sprintf("%s/item/%d.json", BASE, id)
2019-11-21 16:59:52 +00:00
resp, err := get(u)
if err != nil {
return Item{}, err
}
dec := json.NewDecoder(resp.Body)
i := Item{}
if err := dec.Decode(&i); err != nil {
return Item{}, err
}
return i, nil
}
type Items []Item
func (is Items) Titles() string {
out := ""
for i, v := range is {
if i > 0 {
out += ", "
}
out += fmt.Sprintf("<%s|%s>", v.URL, v.Title)
}
return out
}