Skip to content

Instantly share code, notes, and snippets.

@se1983
Last active January 26, 2020 23:56
Show Gist options
  • Save se1983/5af631619054e4d71b44e9f915beb40f to your computer and use it in GitHub Desktop.
Save se1983/5af631619054e4d71b44e9f915beb40f to your computer and use it in GitHub Desktop.
request and marshal reddit data with rust
use ureq;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::error::Error;
#[derive(Serialize, Deserialize)]
struct Data {
title: String,
author: String,
subreddit: String,
ups: i32,
}
#[derive(Serialize, Deserialize)]
struct Post {
data: Data
}
#[derive(Serialize, Deserialize)]
struct Posts {
children: Vec<Post>
}
#[derive(Serialize, Deserialize)]
struct RedditSite {
data: Posts
}
fn truncated(word: String, length: usize) -> String {
match word.chars().count().cmp(&length) {
Ordering::Greater => word.chars()
// convert the String via collect into a char vector.
// The vector has Slice implemented
// After the slicing operation use collect to rebuild the String object.
.collect::<Vec<_>>()[0..(length - 4)]
.iter().cloned().collect::<String>() + " ...",
_ => word,
}
}
fn gather_site(subreddit: &str) -> String {
let url = format!("https://www.reddit.com/r/{}.json?limit=99", subreddit);
let resp = ureq::get(&url).call();
let site_body = resp
.into_string()
.unwrap();
site_body
}
fn deserialize(data: &String) -> Result<RedditSite, Box<dyn Error>> {
let serialized_data: RedditSite = serde_json::from_str(data)?;
Ok(serialized_data)
}
fn main() {
// sync post request of some json.
let body = gather_site("rust");
let all = deserialize(&body).unwrap();
for post in all.data.children {
println!("- \t{:<20} wrote {:<50} in {} and got {:^5} upvotes.",
truncated(post.data.author.clone(), 20),
truncated(post.data.title.clone(), 50),
post.data.subreddit,
post.data.ups,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment