Skip to content

Instantly share code, notes, and snippets.

@panicbit
Last active January 16, 2016 21:43
Show Gist options
  • Save panicbit/c5db358e1901033a6d95 to your computer and use it in GitHub Desktop.
Save panicbit/c5db358e1901033a6d95 to your computer and use it in GitHub Desktop.
extern crate hyper;
extern crate rustc_serialize;
extern crate url;
use rustc_serialize::json::Json;
use url::Url;
use std::io::Read;
use hyper::Client;
use hyper::header::Connection;
pub struct SearchResult {
pub url: String,
pub title: String,
pub desc: String
}
fn parse_results(resp: String) -> Vec<SearchResult> {
Json::from_str(&resp).unwrap().find_path(&["responseData", "results"])
.and_then(Json::as_array).unwrap()
.into_iter()
.map(|val| {
let val = val.as_object().unwrap();
SearchResult {
url: val.get("url").and_then(Json::as_string).map(str::to_string).unwrap(),
title: val.get("titleNoFormatting").and_then(Json::as_string).map(str::to_string).unwrap(),
desc: val.get("content").and_then(Json::as_string).map(str::to_string).unwrap(),
}
})
.collect()
}
fn retrieve(url: Url) -> Vec<SearchResult> {
let client = Client::new();
let mut res = client.get(url)
.header(Connection::close())
.send().unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
parse_results(body)
}
pub fn search(query: &str, max_results: i32) -> Vec<SearchResult> {
let mut url = Url::parse("http://ajax.googleapis.com/ajax/services/search/web").unwrap();
let max_results = &max_results.to_string();
url.set_query_from_pairs(&[
("v" , "1.0"),
("rsz", max_results),
("q" , query)
]);
retrieve(url)
}
fn main() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment