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

46 lines
909 B
Go
Raw Permalink 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 := ""
2019-12-20 18:31:05 +00:00
for _, v := range is {
hnURL := fmt.Sprintf("https://news.ycombinator.com/item?id=%d", v.ID)
if v.URL == "" {
out += fmt.Sprintf("• %s %s (%s)\n", v.Bid, v.Title, hnURL)
} else {
out += fmt.Sprintf("• %s %s (%s)\n", v.Bid, v.Title, hnURL)
}
2019-11-21 16:59:52 +00:00
}
return out
}