Fetch weather data
- Fetch weather data from the url using the api key, city id, and units config
This commit is contained in:
parent
8661ea87db
commit
bebfc6887f
@ -7,4 +7,6 @@ edition = "2024"
|
||||
toml = "0.9.6"
|
||||
dirs = "6.0.0"
|
||||
serde = { version = "1.0.225", features = ["derive"] }
|
||||
reqwest = {version = "0.12.23", features = ["blocking"] }
|
||||
serde_json = "1.0.145"
|
||||
|
||||
|
31
src/main.rs
31
src/main.rs
@ -1,11 +1,12 @@
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use reqwest::blocking;
|
||||
use serde::Deserialize;
|
||||
use std::fs;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct General {
|
||||
api_key: String,
|
||||
city_id: String,
|
||||
units: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@ -13,18 +14,22 @@ struct Config {
|
||||
general: General,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut config_file_path = PathBuf::from(
|
||||
dirs::config_dir().expect("No config dir found")
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut config_path = dirs::config_dir().ok_or("No config dir found")?;
|
||||
config_path.push("candywidgets/openweathermap.toml");
|
||||
|
||||
let config_str = fs::read_to_string(&config_path)
|
||||
.map_err(|_| format!("Failed to read config: {}", config_path.display()))?;
|
||||
|
||||
let config: Config = toml::from_str(&config_str)?;
|
||||
|
||||
let url = format!(
|
||||
"https://api.openweathermap.org/data/2.5/weather?units={}&id={}&appid={}",
|
||||
config.general.units, config.general.city_id, config.general.api_key
|
||||
);
|
||||
config_file_path.push("candywidgets/openweathermap.toml");
|
||||
|
||||
let toml_content = fs::read_to_string(&config_file_path)
|
||||
.expect("Failed to read config file");
|
||||
let resp = blocking::get(&url)?.text()?;
|
||||
println!("Weather report:\n{resp}");
|
||||
|
||||
let config: Config = toml::from_str(&toml_content)
|
||||
.expect("Failed to parse TOML");
|
||||
|
||||
println!("City ID: {}", config.general.city_id);
|
||||
println!("API Key: {}", config.general.api_key);
|
||||
Ok(())
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user