From f5c4671bfbad96bf346bd7e9a21fc4317b4959df Mon Sep 17 00:00:00 2001 From: Indrajith K L Date: Sat, 3 Dec 2022 17:00:20 +0530 Subject: Adds most of the tools --- v_windows/v/examples/news_fetcher.v | 49 +++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 v_windows/v/examples/news_fetcher.v (limited to 'v_windows/v/examples/news_fetcher.v') diff --git a/v_windows/v/examples/news_fetcher.v b/v_windows/v/examples/news_fetcher.v new file mode 100644 index 0000000..e724fba --- /dev/null +++ b/v_windows/v/examples/news_fetcher.v @@ -0,0 +1,49 @@ +// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved. +// Use of this source code is governed by an MIT license +// that can be found in the LICENSE file. +import net.http +import json +import sync.pool + +struct Story { + title string + url string +} + +fn worker_fetch(p &pool.PoolProcessor, cursor int, worker_id int) voidptr { + id := p.get_item(cursor) + resp := http.get('https://hacker-news.firebaseio.com/v0/item/${id}.json') or { + println('failed to fetch data from /v0/item/${id}.json') + return pool.no_result + } + story := json.decode(Story, resp.text) or { + println('failed to decode a story') + return pool.no_result + } + println('# $cursor) $story.title | $story.url') + return pool.no_result +} + +// Fetches top HN stories in parallel, depending on how many cores you have +fn main() { + resp := http.get('https://hacker-news.firebaseio.com/v0/topstories.json') or { + println('failed to fetch data from /v0/topstories.json') + return + } + mut ids := json.decode([]int, resp.text) or { + println('failed to decode topstories.json') + return + } + if ids.len > 10 { + ids = ids[0..10] + } + mut fetcher_pool := pool.new_pool_processor( + callback: worker_fetch + ) + // NB: if you do not call set_max_jobs, the pool will try to use an optimal + // 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 ) + fetcher_pool.work_on_items(ids) +} -- cgit v1.2.3