kodumaro_http_cli/cli/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
mod cli_bool;
mod param;
mod util;
use std::{env::consts, str::FromStr};
use base64::{engine, Engine};
use clap::{ArgAction, Parser, Subcommand};
use cli_bool::CliBool;
use eyre::eyre;
pub use param::Param;
use reqwest::{header::{HeaderName, HeaderValue}, redirect::Policy, Method, Request, Url};
use serde_json::Value;
use util::parse_string;
#[derive(Debug, Parser)]
#[command(about, author, name = "http", version)]
pub struct Cli {
#[command(subcommand)]
pub verb: Verb,
/// data items from the command line are serialized as a JSON object
#[arg(short, long, action = ArgAction::SetTrue, default_value_t = true)]
pub json: bool,
/// data items from the command line are serialized as form fields
#[arg(short, long, action = ArgAction::SetTrue)]
pub form: bool,
// /// similar to --form, but always sends a multipart/form-data request (i.e., even without files)
// #[arg(long, action = ArgAction::SetTrue)]
// pub multipart: bool,
// /// specifies a custom boundary string for multipart/form-data requests
// #[arg(long)]
// pub boundary: Option<String>,
/// allows you to pass raw request data without extra processing
#[arg(long)]
pub raw: Option<String>,
/// save output to file instead of stdout
#[arg(short, long)]
pub output: Option<String>,
/// do not print the response body to stdout; rather, download it and store it in a file
#[arg(short, long)]
pub download: bool,
// TODO: support --continue (-c)
// TODO: support --session
/// basic authentication (user[:password]) or bearer token
#[arg(short, long)]
pub auth: Option<String>,
/// follows Location redirects
#[arg(short = 'F', long, action = ArgAction::SetTrue)]
pub follow: bool,
/// when following redirects, max redirects
#[arg(long, default_value_t = 30)]
pub max_redirects: usize,
/// set to "no" (or "false") to skip checking the host's SSL certificate
#[arg(long, default_value_t = CliBool::Yes)]
pub verify: CliBool,
/// Show headers
#[arg(short, long, action = ArgAction::SetTrue)]
pub verbose: bool,
}
#[derive(Debug, Subcommand)]
pub enum Verb {
/// performs a CONNECT request
#[command()]
Connect {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value and/or querystring==value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a DELETE request
#[command()]
Delete {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value and/or querystring==value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a GET request
#[command()]
Get {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value and/or querystring==value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a HEAD request
#[command()]
Head {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value and/or querystring==value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a OPTION request
#[command()]
Option {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value and/or querystring==value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a PATCH request
#[command()]
Patch {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value, querystring==value, and/or payload=value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a POST request
#[command()]
Post {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value, querystring==value, and/or payload=value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a PUT request
#[command()]
Put {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value, querystring==value, and/or payload=value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
/// performs a TRACE request
#[command()]
Trace {
/// the URL to connect to
#[arg()]
url: Url,
/// header:value and/or querystring==value; @value means value from file content
#[arg()]
params: Vec<Param>,
},
}
impl Cli {
pub fn payload(&self) -> Result<Value, Option<eyre::ErrReport>> {
if let Some(raw) = &self.raw {
return Ok(Value::String(parse_string(raw.to_string())?));
}
let mut payload: Option<Value> = None;
for param in self.verb.params().iter() {
if let Param::Payload(param) = param {
match payload {
None => payload.insert(param.clone()).ignore(),
Some(Value::Object(ref mut payload)) =>
match param {
Value::Object(param) => payload.extend(
param.iter()
.map(|(k, v)| (k.to_owned(), v.clone()))
).ignore(),
_ => return Err(Some(eyre!("invalid payload"))),
},
Some(_) => return Err(Some(eyre!("invalid payload"))),
}
}
}
match payload {
Some(payload) => Ok(payload),
None => Err(None),
}
}
}
impl Verb {
pub fn url(&self) -> &Url {
match self {
Verb::Connect { url, .. } => url,
Verb::Delete { url, .. } => url,
Verb::Get { url, .. } => url,
Verb::Head { url, .. } => url,
Verb::Option { url, .. } => url,
Verb::Patch { url, .. } => url,
Verb::Post { url, .. } => url,
Verb::Put { url, .. } => url,
Verb::Trace { url, .. } => url,
}
}
pub fn params(&self) -> &Vec<Param> {
match self {
Verb::Connect { params, .. } => params,
Verb::Delete { params, .. } => params,
Verb::Get { params, .. } => params,
Verb::Head { params, .. } => params,
Verb::Option { params, .. } => params,
Verb::Patch { params, .. } => params,
Verb::Post { params, .. } => params,
Verb::Put { params, .. } => params,
Verb::Trace { params, .. } => params,
}
}
}
impl From<&Verb> for Method {
fn from(value: &Verb) -> Self {
match value {
Verb::Connect { .. } => Method::CONNECT,
Verb::Delete { .. } => Method::DELETE,
Verb::Get { .. } => Method::GET,
Verb::Head { .. } => Method::HEAD,
Verb::Option { .. } => Method::OPTIONS,
Verb::Patch { .. } => Method::PATCH,
Verb::Post { .. } => Method::POST,
Verb::Put { .. } => Method::PUT,
Verb::Trace { .. } => Method::TRACE,
}
}
}
impl TryFrom<&Cli> for Request {
type Error = eyre::Error;
fn try_from(value: &Cli) -> Result<Self, Self::Error> {
if value.json && value.form {
return Err(eyre!("--json and --form are mutually exclusive"));
// if (value.json && value.form)
// || (value.json && value.multipart)
// || (value.form && value.multipart) {
// return Err(eyre!("--json, --form, and --multipart are mutually exclusive"));
}
let method: Method = (&value.verb).into();
let mut url = value.verb.url().clone();
let mut headers: Vec<(String, String)> = vec![];
let mut user_agent_set = false;
let user_agent = reqwest::header::USER_AGENT.to_string();
for param in value.verb.params().iter() {
match param {
Param::Header(name, value) => {
if user_agent == **name {
user_agent_set = true;
}
headers.push((name.to_owned(), value.to_owned()));
}
Param::Query(key, value) => url.query_pairs_mut()
.append_pair(&key, &value)
.ignore(),
_ => (),
}
}
if !user_agent_set {
headers.push((
user_agent.to_owned(),
format!(
"Mozilla/5.0 ({} {}) AppleWebKit/537.36 (KHTML like Gecko) {}/{} Chrome/129.0.0.0 Safari/537.36",
consts::OS,
consts::ARCH,
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION"),
),
));
}
let mut request = Request::new(method, url);
for (name, value) in headers.iter() {
let _ = request.headers_mut().insert(
HeaderName::from_str(name)?,
HeaderValue::from_str(value)?,
);
}
if let Some(auth) = &value.auth {
if let Some((username, password)) = auth.split_once(':') {
let auth = format!("{}:{}", username, password);
let engine = engine::general_purpose::STANDARD;
let auth = engine.encode(auth.into_bytes());
let _ = request.headers_mut().insert(
reqwest::header::AUTHORIZATION,
HeaderValue::from_str(&format!("Basic {}", auth))?,
);
} else {
let _ = request.headers_mut().insert(
reqwest::header::AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", auth))?,
);
}
}
Ok(request)
}
}
impl From<&Cli> for Policy {
fn from(value: &Cli) -> Self {
if value.follow {
Policy::limited(value.max_redirects)
} else {
Policy::none()
}
}
}
trait Ignore {
fn ignore(&self) {}
}
impl<T> Ignore for T {
}