面试题答案
一键面试use std::collections::HashMap;
use std::fmt::Display;
use std::net::Uri;
#[derive(Debug)]
enum Method {
GET,
POST,
}
#[derive(Debug)]
enum RequestError {
InvalidUrl,
UnsupportedMethod,
}
impl Display for RequestError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RequestError::InvalidUrl => write!(f, "Invalid URL"),
RequestError::UnsupportedMethod => write!(f, "Unsupported method"),
}
}
}
fn send_request(
url: Option<&str>,
method: Option<Method>,
headers: Option<HashMap<String, String>>,
body: Option<Vec<u8>>,
) -> Result<(), RequestError> {
let url = match url {
Some(u) => match Uri::try_from(u) {
Ok(uri) => uri,
Err(_) => return Err(RequestError::InvalidUrl),
},
None => return Err(RequestError::InvalidUrl),
};
let method = match method {
Some(m) => m,
None => return Err(RequestError::UnsupportedMethod),
};
let headers = headers.unwrap_or_default();
let body = body.unwrap_or_default();
// 这里可以进行实际的网络请求操作,暂时省略
println!("Request to: {:?}, Method: {:?}, Headers: {:?}, Body: {:?}", url, method, headers, body);
Ok(())
}
你可以通过以下方式调用这个函数:
fn main() {
let mut headers = HashMap::new();
headers.insert("Content-Type".to_string(), "application/json".to_string());
let result = send_request(
Some("https://example.com"),
Some(Method::GET),
Some(headers),
Some(b"test body".to_vec()),
);
match result {
Ok(_) => println!("Request sent successfully"),
Err(e) => println!("Error: {}", e),
}
}