-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (71 loc) · 1.54 KB
/
main.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"runtime"
"time"
"github.com/fatih/color"
)
type HackerStory struct {
Title string `json: "title"`
Url string `json: "url"`
}
func openbrowser(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
if err != nil {
log.Fatal(err)
}
}
func main() {
arg := os.Args[1]
rand.Seed(time.Now().UnixNano())
topStoriesUrl := fmt.Sprintf("https://hacker-news.firebaseio.com/v0/%sstories.json?print=pretty", arg)
resp, err := http.Get(topStoriesUrl)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var topStories []int64
err = json.Unmarshal(body, &topStories)
if err != nil {
panic(err)
}
randomStoryId := topStories[rand.Intn(len(topStories))]
randomStoryUrl := fmt.Sprintf("https://hacker-news.firebaseio.com/v0/item/%d.json?print=pretty", randomStoryId)
resp, err = http.Get(randomStoryUrl)
if err != nil {
panic(err)
}
body, err = io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var hackerStory HackerStory
err = json.Unmarshal(body, &hackerStory)
if err != nil {
panic(err)
}
color.Green(hackerStory.Title)
color.White(hackerStory.Url)
openbrowser(hackerStory.Url)
}