-
Notifications
You must be signed in to change notification settings - Fork 1
/
orange_site.go
71 lines (59 loc) · 1.31 KB
/
orange_site.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"strconv"
)
func hn(storyType string) string {
items := []int{}
{
url := "https://hacker-news.firebaseio.com/v0/" + storyType + "stories.json"
resp, err := http.Get(url)
checkErr(err)
if resp.StatusCode != 200 {
printResponse(resp)
return resp.Status
}
checkErr(json.NewDecoder(resp.Body).Decode(&items))
}
item := 0
if len(items) == 0 {
return "(no items returned)"
}
if len(items) > 1 {
item = items[rand.Intn(len(items)-1)]
} else {
item = items[0]
}
url := "https://hacker-news.firebaseio.com/v0/item/" + strconv.Itoa(item) + ".json"
resp, err := http.Get(url)
checkErr(err)
if resp.StatusCode != 200 {
printResponse(resp)
return resp.Status
}
var story struct {
Id int `json:"id"`
Title string `json:"title"`
Url string `json:"url"`
}
checkErr(json.NewDecoder(resp.Body).Decode(&story))
ret := story.Title
if story.Url != "" {
ret += " - ." + story.Url
} else {
ret += " - .https://news.ycombinator.com/item?id=" + strconv.Itoa(story.Id)
}
return ret
}
func printResponse(resp *http.Response) {
fmt.Print(resp.Status, "\n")
for k, v := range resp.Header {
fmt.Print(k, ": ", v[0], "\n")
}
body, _ := ioutil.ReadAll(resp.Body)
fmt.Print("\n", string(body), "\n")
}