2022-01-04 12:21:08 +03:00
|
|
|
// Copyright (c) 2019-2022 Alexander Medvednikov. All rights reserved.
|
2019-06-23 05:21:30 +03:00
|
|
|
// Use of this source code is governed by an MIT license
|
|
|
|
// that can be found in the LICENSE file.
|
2019-12-30 07:42:23 +03:00
|
|
|
import net.http
|
2019-06-22 22:51:07 +03:00
|
|
|
import json
|
2021-02-11 11:55:23 +03:00
|
|
|
import sync.pool
|
2019-06-22 22:51:07 +03:00
|
|
|
|
|
|
|
struct Story {
|
|
|
|
title string
|
2019-12-22 01:41:42 +03:00
|
|
|
url string
|
2019-06-22 22:51:07 +03:00
|
|
|
}
|
|
|
|
|
2022-11-10 21:19:19 +03:00
|
|
|
fn worker_fetch(mut p pool.PoolProcessor, cursor int, worker_id int) voidptr {
|
2022-11-26 19:23:26 +03:00
|
|
|
id := p.get_item[int](cursor)
|
2020-03-04 22:28:42 +03:00
|
|
|
resp := http.get('https://hacker-news.firebaseio.com/v0/item/${id}.json') or {
|
|
|
|
println('failed to fetch data from /v0/item/${id}.json')
|
2021-02-11 11:55:23 +03:00
|
|
|
return pool.no_result
|
2020-03-04 22:28:42 +03:00
|
|
|
}
|
2022-05-29 20:27:18 +03:00
|
|
|
story := json.decode(Story, resp.body) or {
|
2020-03-04 22:28:42 +03:00
|
|
|
println('failed to decode a story')
|
2021-02-11 11:55:23 +03:00
|
|
|
return pool.no_result
|
2019-06-22 22:51:07 +03:00
|
|
|
}
|
2022-11-15 16:53:13 +03:00
|
|
|
println('# ${cursor}) ${story.title} | ${story.url}')
|
2021-02-11 11:55:23 +03:00
|
|
|
return pool.no_result
|
2019-06-22 22:51:07 +03:00
|
|
|
}
|
|
|
|
|
2020-03-04 22:28:42 +03:00
|
|
|
// Fetches top HN stories in parallel, depending on how many cores you have
|
2019-06-22 22:51:07 +03:00
|
|
|
fn main() {
|
2019-07-29 20:18:26 +03:00
|
|
|
resp := http.get('https://hacker-news.firebaseio.com/v0/topstories.json') or {
|
|
|
|
println('failed to fetch data from /v0/topstories.json')
|
|
|
|
return
|
|
|
|
}
|
2022-05-29 20:27:18 +03:00
|
|
|
ids := json.decode([]int, resp.body) or {
|
2019-07-29 20:18:26 +03:00
|
|
|
println('failed to decode topstories.json')
|
2019-06-22 22:51:07 +03:00
|
|
|
return
|
2022-04-10 11:11:53 +03:00
|
|
|
}#[0..10]
|
2021-02-11 11:55:23 +03:00
|
|
|
mut fetcher_pool := pool.new_pool_processor(
|
2020-03-04 22:28:42 +03:00
|
|
|
callback: worker_fetch
|
2021-02-11 11:55:23 +03:00
|
|
|
)
|
2022-03-06 20:01:22 +03:00
|
|
|
// Note: if you do not call set_max_jobs, the pool will try to use an optimal
|
2020-03-04 22:28:42 +03:00
|
|
|
// number of threads, one per each core in your system, which in most
|
|
|
|
// cases is what you want anyway... You can override the automatic choice
|
|
|
|
// by setting the VJOBS environment variable too.
|
|
|
|
// fetcher_pool.set_max_jobs( 4 )
|
2021-02-11 11:55:23 +03:00
|
|
|
fetcher_pool.work_on_items(ids)
|
2019-06-22 22:51:07 +03:00
|
|
|
}
|