Skip to content

Instantly share code, notes, and snippets.

@kilroyjones
Created July 31, 2020 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kilroyjones/43848beb02ffe16dec9bfc88a884ee6e to your computer and use it in GitHub Desktop.
Save kilroyjones/43848beb02ffe16dec9bfc88a884ee6e to your computer and use it in GitHub Desktop.
Async openweather example
async fn get_response(location: &str) -> Result<String, reqwest::Error> {
let base_http = "https://api.openweathermap.org/data/2.5/weather?q=".to_string();
let units = "metric";
let addr = base_http + &location + "&appid=" + API_KEY + "&units=" + &units;
let json = reqwest::get(&addr)
.await?
.text()
.await?;
Ok(json)
}
async fn parse_json(json: &str) -> Result<OpenWeatherData, serde_json::error::Error> {
let data: OpenWeatherData = serde_json::from_str(&json.to_string())?;
Ok(data)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let response = get_response("Taipei").await;
let json = match response {
Ok(test) => test,
Err(_) => "Error in processing".to_string(),
};
println!("{}", json);
let weather_data = parse_json(&json).await;
match weather_data {
Ok(data) => println!("{}", data.main.temp),
Err(_) => println!("Error in parsing"),
};
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment