Last active
March 15, 2019 21:31
-
-
Save oconnor663/7a9035c4dcf0e364db10a07f428a3a59 to your computer and use it in GitHub Desktop.
Rust HN fetch example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "fetch_hn" | |
version = "0.1.0" | |
edition = "2018" | |
[dependencies] | |
serde = { version = "1.0.89", features = ["derive"] } | |
reqwest = "0.9.11" | |
crossbeam-utils = "0.6.5" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use serde::Deserialize; | |
use std::sync::Mutex; | |
const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json"; | |
const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item"; | |
#[derive(Deserialize)] | |
struct Story { | |
title: String, | |
} | |
fn main() { | |
let story_ids: Vec<u64> = reqwest::get(STORIES_URL).unwrap().json().unwrap(); | |
// AtomicUsize would be simpler than Mutex here, but the point of this is | |
// to give a Mutex example. | |
let cursor = Mutex::new(0); | |
crossbeam_utils::thread::scope(|s| { | |
for _ in 0..8 { | |
s.spawn(|_| loop { | |
let index = { | |
let mut cursor_guard = cursor.lock().unwrap(); | |
let index = *cursor_guard; | |
if index >= story_ids.len() { | |
return; | |
} | |
*cursor_guard += 1; | |
index | |
}; | |
let story_url = format!("{}/{}.json", ITEM_URL_BASE, story_ids[index]); | |
let story: Story = reqwest::get(&story_url).unwrap().json().unwrap(); | |
println!("{}", story.title); | |
}); | |
} | |
}) | |
.unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment