├── README.md
└── hn.v
/README.md:
--------------------------------------------------------------------------------
1 | # HN top
2 |
3 |
4 |
5 |
6 |
7 |
8 | ## Run
9 |
10 | - `v run hn.v`
11 |
12 | ## Compile
13 |
14 | - `v -o bin/hntop -prod hn.v`
15 |
--------------------------------------------------------------------------------
/hn.v:
--------------------------------------------------------------------------------
1 | import os
2 | import json
3 | import term
4 | import flag
5 | import net.http
6 |
7 | const (
8 | api = 'https://hacker-news.firebaseio.com/v0'
9 | )
10 |
11 | struct Story {
12 | by string
13 | descendants int
14 | kids []int
15 | id int
16 | score int
17 | // time int
18 | title string
19 | typ string [json:'type']
20 | url string
21 | }
22 |
23 | fn fetch_story(id int) Story {
24 | text := http.get_text('${api}/item/${id}.json')
25 | story := json.decode(Story, text) or { exit(1) }
26 | return story
27 | }
28 |
29 | fn fetch_top_stories(num int) []Story {
30 | text := http.get_text('${api}/topstories.json')
31 |
32 | stories_ids := json.decode([]int, text) or { exit(1) }
33 |
34 | stories_top_ids := stories_ids[..num]
35 |
36 | return stories_top_ids.map(fetch_story(it))
37 | }
38 |
39 | fn main() {
40 | mut fp := flag.new_flag_parser(os.args)
41 | fp.application('hn_top')
42 | fp.version('v0.1.0')
43 | fp.description('Show top HN news')
44 | fp.skip_executable()
45 | top_num := fp.int('num', `n`, 5, 'number of top news to show')
46 | source_urls := fp.bool('source_urls', `u`, false, 'show source urls')
47 |
48 | fp.finalize() or {
49 | eprintln(err)
50 | println(fp.usage())
51 | return
52 | }
53 |
54 | println('Fetching last stories...')
55 | stories := fetch_top_stories(top_num)
56 | term.cursor_up(1)
57 | term.erase_toend()
58 |
59 | // Print stories
60 | for i, story in stories {
61 | len := '${i + 1}'.len
62 | indent := ' '.repeat(2 + len)
63 | println('${i + 1}. ${term.bold(story.title)}')
64 | println('${indent}score: ${story.score} comments: ${story.descendants} user: ${story.by}')
65 | url := 'url: https://news.ycombinator.com/item?id=${story.id}'
66 | println('${indent}${term.dim(url)}')
67 |
68 | if source_urls {
69 | source_url := 'source: ${story.url}'
70 | println('${indent}${term.dim(source_url)}')
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------