HTTP HEAD / PATCH / PUT / DELETE commands (#8144)

# Description

Based on https://github.com/nushell/nushell/pull/8135.

Add the remaining HTTP commands:

- Head
- Patch
- Put
- Delete

It should finally resolve the issue
https://github.com/nushell/nushell/issues/2741

# User-Facing Changes

New sub HTTP commands.

# Tests + Formatting

Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
This commit is contained in:
Jérémy Audiger 2023-02-24 00:52:12 +01:00 committed by GitHub
parent 3fb1e37473
commit 83087e0f9d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 907 additions and 59 deletions

View File

@ -440,8 +440,12 @@ pub fn create_default_context() -> EngineState {
// Network
bind_command! {
Http,
HttpDelete,
HttpGet,
HttpHead,
HttpPatch,
HttpPost,
HttpPut,
Url,
UrlBuildQuery,
UrlEncode,

View File

@ -4,7 +4,9 @@ use base64::engine::GeneralPurpose;
use base64::{alphabet, Engine};
use nu_protocol::ast::Call;
use nu_protocol::engine::{EngineState, Stack};
use nu_protocol::{BufferedReader, PipelineData, RawStream, ShellError, Span, Value};
use nu_protocol::{
BufferedReader, IntoPipelineData, PipelineData, RawStream, ShellError, Span, Value,
};
use reqwest::blocking::{RequestBuilder, Response};
use reqwest::{blocking, Error, StatusCode};
use std::collections::HashMap;
@ -23,8 +25,8 @@ pub enum BodyType {
// Only panics if the user agent is invalid but we define it statically so either
// it always or never fails
pub fn http_client(allow_insecure: bool) -> reqwest::blocking::Client {
reqwest::blocking::Client::builder()
pub fn http_client(allow_insecure: bool) -> blocking::Client {
blocking::Client::builder()
.user_agent("nushell")
.danger_accept_invalid_certs(allow_insecure)
.build()
@ -54,7 +56,7 @@ pub fn http_parse_url(
}
pub fn response_to_buffer(
response: blocking::Response,
response: Response,
engine_state: &EngineState,
span: Span,
) -> PipelineData {
@ -263,6 +265,51 @@ pub fn request_add_custom_headers(
Ok(request)
}
fn handle_response_error(span: Span, requested_url: &String, response: Error) -> ShellError {
// Explicitly turn 4xx and 5xx statuses into errors.
if response.is_timeout() {
ShellError::NetworkFailure(format!("Request to {requested_url} has timed out"), span)
} else if response.is_status() {
match response.status() {
Some(err_code) if err_code == StatusCode::NOT_FOUND => ShellError::NetworkFailure(
format!("Requested file not found (404): {requested_url:?}"),
span,
),
Some(err_code) if err_code == StatusCode::MOVED_PERMANENTLY => {
ShellError::NetworkFailure(
format!("Resource moved permanently (301): {requested_url:?}"),
span,
)
}
Some(err_code) if err_code == StatusCode::BAD_REQUEST => {
ShellError::NetworkFailure(format!("Bad request (400) to {requested_url:?}"), span)
}
Some(err_code) if err_code == StatusCode::FORBIDDEN => ShellError::NetworkFailure(
format!("Access forbidden (403) to {requested_url:?}"),
span,
),
_ => ShellError::NetworkFailure(
format!(
"Cannot make request to {:?}. Error is {:?}",
requested_url,
response.to_string()
),
span,
),
}
} else {
ShellError::NetworkFailure(
format!(
"Cannot make request to {:?}. Error is {:?}",
requested_url,
response.to_string()
),
span,
)
}
}
pub fn request_handle_response(
engine_state: &EngineState,
stack: &mut Stack,
@ -271,7 +318,6 @@ pub fn request_handle_response(
raw: bool,
response: Result<Response, Error>,
) -> Result<PipelineData, ShellError> {
// Explicitly turn 4xx and 5xx statuses into errors.
match response {
Ok(resp) => match resp.headers().get("content-type") {
Some(content_type) => {
@ -340,44 +386,40 @@ pub fn request_handle_response(
}
None => Ok(response_to_buffer(resp, engine_state, span)),
},
Err(e) if e.is_timeout() => Err(ShellError::NetworkFailure(
format!("Request to {requested_url} has timed out"),
span,
)),
Err(e) if e.is_status() => match e.status() {
Some(err_code) if err_code == StatusCode::NOT_FOUND => Err(ShellError::NetworkFailure(
format!("Requested file not found (404): {requested_url:?}"),
span,
)),
Some(err_code) if err_code == StatusCode::MOVED_PERMANENTLY => {
Err(ShellError::NetworkFailure(
format!("Resource moved permanently (301): {requested_url:?}"),
span,
))
}
Some(err_code) if err_code == StatusCode::BAD_REQUEST => Err(
ShellError::NetworkFailure(format!("Bad request (400) to {requested_url:?}"), span),
),
Some(err_code) if err_code == StatusCode::FORBIDDEN => Err(ShellError::NetworkFailure(
format!("Access forbidden (403) to {requested_url:?}"),
span,
)),
_ => Err(ShellError::NetworkFailure(
format!(
"Cannot make request to {:?}. Error is {:?}",
requested_url,
e.to_string()
),
span,
)),
},
Err(e) => Err(ShellError::NetworkFailure(
format!(
"Cannot make request to {:?}. Error is {:?}",
requested_url,
e.to_string()
),
span,
)),
Err(e) => Err(handle_response_error(span, requested_url, e)),
}
}
pub fn request_handle_response_headers(
span: Span,
requested_url: &String,
response: Result<Response, Error>,
) -> Result<PipelineData, ShellError> {
match response {
Ok(resp) => {
let cols: Vec<String> = resp.headers().keys().map(|name| name.to_string()).collect();
let mut vals = Vec::with_capacity(cols.len());
for value in resp.headers().values() {
match value.to_str() {
Ok(str_value) => vals.push(Value::String {
val: str_value.to_string(),
span,
}),
Err(err) => {
return Err(ShellError::GenericError(
format!("Failure when converting header value: {err}"),
"".to_string(),
None,
Some("Failure when converting header value".to_string()),
Vec::new(),
))
}
}
}
Ok(Value::Record { cols, vals, span }.into_pipeline_data())
}
Err(e) => Err(handle_response_error(span, requested_url, e)),
}
}

View File

@ -0,0 +1,211 @@
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
use crate::network::http::client::{
http_client, http_parse_url, request_add_authorization_header, request_add_custom_headers,
request_handle_response, request_set_body, request_set_timeout,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"http delete"
}
fn signature(&self) -> Signature {
Signature::build("http delete")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.required(
"URL",
SyntaxShape::String,
"the URL to fetch the contents from",
)
.named(
"user",
SyntaxShape::Any,
"the username when authenticating",
Some('u'),
)
.named(
"password",
SyntaxShape::Any,
"the password when authenticating",
Some('p'),
)
.named("data", SyntaxShape::Any, "the content to post", Some('d'))
.named(
"content-type",
SyntaxShape::Any,
"the MIME type of content to post",
Some('t'),
)
.named(
"content-length",
SyntaxShape::Any,
"the length of the content being posted",
Some('l'),
)
.named(
"max-time",
SyntaxShape::Int,
"timeout period in seconds",
Some('m'),
)
.named(
"headers",
SyntaxShape::Any,
"custom headers you want to add ",
Some('H'),
)
.switch(
"raw",
"fetch contents as text rather than a table",
Some('r'),
)
.switch(
"insecure",
"allow insecure server connections when using SSL",
Some('k'),
)
.filter()
.category(Category::Network)
}
fn usage(&self) -> &str {
"Delete the specified resource."
}
fn extra_usage(&self) -> &str {
"Performs HTTP DELETE operation."
}
fn search_terms(&self) -> Vec<&str> {
vec!["network", "request", "curl", "wget"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_delete(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "http delete from example.com",
example: "http delete https://www.example.com",
result: None,
},
Example {
description: "http delete from example.com, with username and password",
example: "http delete -u myuser -p mypass https://www.example.com",
result: None,
},
Example {
description: "http delete from example.com, with custom header",
example: "http delete -H [my-header-key my-header-value] https://www.example.com",
result: None,
},
Example {
description: "http delete from example.com, with body",
example: "http delete -d 'body' https://www.example.com",
result: None,
},
Example {
description: "http delete from example.com, with JSON body",
example:
"http delete -t application/json -d { field: value } https://www.example.com",
result: None,
},
]
}
}
struct Arguments {
url: Value,
headers: Option<Value>,
data: Option<Value>,
content_type: Option<String>,
content_length: Option<String>,
raw: bool,
insecure: Option<bool>,
user: Option<String>,
password: Option<String>,
timeout: Option<Value>,
}
fn run_delete(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args = Arguments {
url: call.req(engine_state, stack, 0)?,
headers: call.get_flag(engine_state, stack, "headers")?,
data: call.get_flag(engine_state, stack, "data")?,
content_type: call.get_flag(engine_state, stack, "content-type")?,
content_length: call.get_flag(engine_state, stack, "content-length")?,
raw: call.has_flag("raw"),
insecure: call.get_flag(engine_state, stack, "insecure")?,
user: call.get_flag(engine_state, stack, "user")?,
password: call.get_flag(engine_state, stack, "password")?,
timeout: call.get_flag(engine_state, stack, "timeout")?,
};
helper(engine_state, stack, call, args)
}
// Helper function that actually goes to retrieve the resource from the url given
// The Option<String> return a possible file extension which can be used in AutoConvert commands
fn helper(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
args: Arguments,
) -> Result<PipelineData, ShellError> {
let span = args.url.span()?;
let (requested_url, url) = http_parse_url(call, span, args.url)?;
let client = http_client(args.insecure.is_some());
let mut request = client.delete(url);
if let Some(data) = args.data {
request = request_set_body(args.content_type, args.content_length, data, request)?;
}
request = request_set_timeout(args.timeout, request)?;
request = request_add_authorization_header(args.user, args.password, request);
request = request_add_custom_headers(args.headers, request)?;
let response = request.send().and_then(|r| r.error_for_status());
request_handle_response(
engine_state,
stack,
span,
&requested_url,
args.raw,
response,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -21,6 +21,7 @@ impl Command for SubCommand {
fn signature(&self) -> Signature {
Signature::build("http get")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.required(
"URL",
SyntaxShape::String,
@ -98,33 +99,33 @@ impl Command for SubCommand {
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_post(engine_state, stack, call, input)
run_get(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "http get content from example.com",
description: "Get content from example.com",
example: "http get https://www.example.com",
result: None,
},
Example {
description: "http get content from example.com, with username and password",
description: "Get content from example.com, with username and password",
example: "http get -u myuser -p mypass https://www.example.com",
result: None,
},
Example {
description: "http get content from example.com, with custom header",
description: "Get content from example.com, with custom header",
example: "http get -H [my-header-key my-header-value] https://www.example.com",
result: None,
},
Example {
description: "http get from example.com, with body",
description: "Get content from example.com, with body",
example: "http get -d 'body' https://www.example.com",
result: None,
},
Example {
description: "http get from example.com, with JSON body",
description: "Get content from example.com, with JSON body",
example: "http get -t application/json -d { field: value } https://www.example.com",
result: None,
},
@ -145,7 +146,7 @@ struct Arguments {
timeout: Option<Value>,
}
fn run_post(
fn run_get(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
@ -197,3 +198,15 @@ fn helper(
response,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -0,0 +1,159 @@
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
use crate::network::http::client::{
http_client, http_parse_url, request_add_authorization_header, request_add_custom_headers,
request_handle_response_headers, request_set_timeout,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"http head"
}
fn signature(&self) -> Signature {
Signature::build("http head")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.required(
"URL",
SyntaxShape::String,
"the URL to fetch the contents from",
)
.named(
"user",
SyntaxShape::Any,
"the username when authenticating",
Some('u'),
)
.named(
"password",
SyntaxShape::Any,
"the password when authenticating",
Some('p'),
)
.named(
"max-time",
SyntaxShape::Int,
"timeout period in seconds",
Some('m'),
)
.named(
"headers",
SyntaxShape::Any,
"custom headers you want to add ",
Some('H'),
)
.switch(
"insecure",
"allow insecure server connections when using SSL",
Some('k'),
)
.filter()
.category(Category::Network)
}
fn usage(&self) -> &str {
"Get the headers from a URL."
}
fn extra_usage(&self) -> &str {
"Performs HTTP HEAD operation."
}
fn search_terms(&self) -> Vec<&str> {
vec!["network", "request", "curl", "wget", "headers", "header"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_head(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Get headers from example.com",
example: "http head https://www.example.com",
result: None,
},
Example {
description: "Get headers from example.com, with username and password",
example: "http head -u myuser -p mypass https://www.example.com",
result: None,
},
Example {
description: "Get headers from example.com, with custom header",
example: "http head -H [my-header-key my-header-value] https://www.example.com",
result: None,
},
]
}
}
struct Arguments {
url: Value,
headers: Option<Value>,
insecure: Option<bool>,
user: Option<String>,
password: Option<String>,
timeout: Option<Value>,
}
fn run_head(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args = Arguments {
url: call.req(engine_state, stack, 0)?,
headers: call.get_flag(engine_state, stack, "headers")?,
insecure: call.get_flag(engine_state, stack, "insecure")?,
user: call.get_flag(engine_state, stack, "user")?,
password: call.get_flag(engine_state, stack, "password")?,
timeout: call.get_flag(engine_state, stack, "timeout")?,
};
helper(call, args)
}
// Helper function that actually goes to retrieve the resource from the url given
// The Option<String> return a possible file extension which can be used in AutoConvert commands
fn helper(call: &Call, args: Arguments) -> Result<PipelineData, ShellError> {
let span = args.url.span()?;
let (requested_url, url) = http_parse_url(call, span, args.url)?;
let client = http_client(args.insecure.is_some());
let mut request = client.head(url);
request = request_set_timeout(args.timeout, request)?;
request = request_add_authorization_header(args.user, args.password, request);
request = request_add_custom_headers(args.headers, request)?;
let response = request.send().and_then(|r| r.error_for_status());
request_handle_response_headers(span, &requested_url, response)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -1,8 +1,16 @@
mod client;
mod delete;
mod get;
mod head;
mod http_;
mod patch;
mod post;
mod put;
pub use delete::SubCommand as HttpDelete;
pub use get::SubCommand as HttpGet;
pub use head::SubCommand as HttpHead;
pub use http_::Http;
pub use patch::SubCommand as HttpPatch;
pub use post::SubCommand as HttpPost;
pub use put::SubCommand as HttpPut;

View File

@ -0,0 +1,199 @@
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
use crate::network::http::client::{
http_client, http_parse_url, request_add_authorization_header, request_add_custom_headers,
request_handle_response, request_set_body, request_set_timeout,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"http patch"
}
fn signature(&self) -> Signature {
Signature::build("http patch")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.required("URL", SyntaxShape::String, "the URL to post to")
.required("data", SyntaxShape::Any, "the contents of the post body")
.named(
"user",
SyntaxShape::Any,
"the username when authenticating",
Some('u'),
)
.named(
"password",
SyntaxShape::Any,
"the password when authenticating",
Some('p'),
)
.named(
"content-type",
SyntaxShape::Any,
"the MIME type of content to post",
Some('t'),
)
.named(
"content-length",
SyntaxShape::Any,
"the length of the content being posted",
Some('l'),
)
.named(
"max-time",
SyntaxShape::Int,
"timeout period in seconds",
Some('m'),
)
.named(
"headers",
SyntaxShape::Any,
"custom headers you want to add ",
Some('H'),
)
.switch(
"raw",
"return values as a string instead of a table",
Some('r'),
)
.switch(
"insecure",
"allow insecure server connections when using SSL",
Some('k'),
)
.filter()
.category(Category::Network)
}
fn usage(&self) -> &str {
"Patch a body to a URL."
}
fn extra_usage(&self) -> &str {
"Performs HTTP PATCH operation."
}
fn search_terms(&self) -> Vec<&str> {
vec!["network", "send", "push"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_patch(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Patch content to example.com",
example: "http patch https://www.example.com 'body'",
result: None,
},
Example {
description: "Patch content to example.com, with username and password",
example: "http patch -u myuser -p mypass https://www.example.com 'body'",
result: None,
},
Example {
description: "Patch content to example.com, with custom header",
example: "http patch -H [my-header-key my-header-value] https://www.example.com",
result: None,
},
Example {
description: "Patch content to example.com, with JSON body",
example: "http patch -t application/json https://www.example.com { field: value }",
result: None,
},
]
}
}
struct Arguments {
url: Value,
headers: Option<Value>,
data: Value,
content_type: Option<String>,
content_length: Option<String>,
raw: bool,
insecure: Option<bool>,
user: Option<String>,
password: Option<String>,
timeout: Option<Value>,
}
fn run_patch(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args = Arguments {
url: call.req(engine_state, stack, 0)?,
headers: call.get_flag(engine_state, stack, "headers")?,
data: call.req(engine_state, stack, 1)?,
content_type: call.get_flag(engine_state, stack, "content-type")?,
content_length: call.get_flag(engine_state, stack, "content-length")?,
raw: call.has_flag("raw"),
insecure: call.get_flag(engine_state, stack, "insecure")?,
user: call.get_flag(engine_state, stack, "user")?,
password: call.get_flag(engine_state, stack, "password")?,
timeout: call.get_flag(engine_state, stack, "timeout")?,
};
helper(engine_state, stack, call, args)
}
// Helper function that actually goes to retrieve the resource from the url given
// The Option<String> return a possible file extension which can be used in AutoConvert commands
fn helper(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
args: Arguments,
) -> Result<PipelineData, ShellError> {
let span = args.url.span()?;
let (requested_url, url) = http_parse_url(call, span, args.url)?;
let client = http_client(args.insecure.is_some());
let mut request = client.patch(url);
request = request_set_body(args.content_type, args.content_length, args.data, request)?;
request = request_set_timeout(args.timeout, request)?;
request = request_add_authorization_header(args.user, args.password, request);
request = request_add_custom_headers(args.headers, request)?;
let response = request.send().and_then(|r| r.error_for_status());
request_handle_response(
engine_state,
stack,
span,
&requested_url,
args.raw,
response,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -21,6 +21,7 @@ impl Command for SubCommand {
fn signature(&self) -> Signature {
Signature::build("http post")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.required("URL", SyntaxShape::String, "the URL to post to")
.required("data", SyntaxShape::Any, "the contents of the post body")
.named(
@ -98,23 +99,23 @@ impl Command for SubCommand {
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Post content to url.com",
example: "http post url.com 'body'",
description: "Post content to example.com",
example: "http post https://www.example.com 'body'",
result: None,
},
Example {
description: "Post content to url.com, with username and password",
example: "http post -u myuser -p mypass url.com 'body'",
description: "Post content to example.com, with username and password",
example: "http post -u myuser -p mypass https://www.example.com 'body'",
result: None,
},
Example {
description: "Post content to url.com, with custom header",
example: "http post -H [my-header-key my-header-value] url.com",
description: "Post content to example.com, with custom header",
example: "http post -H [my-header-key my-header-value] https://www.example.com",
result: None,
},
Example {
description: "Post content to url.com, with JSON body",
example: "http post -t application/json url.com { field: value }",
description: "Post content to example.com, with JSON body",
example: "http post -t application/json https://www.example.com { field: value }",
result: None,
},
]
@ -184,3 +185,15 @@ fn helper(
response,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}

View File

@ -0,0 +1,199 @@
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
use crate::network::http::client::{
http_client, http_parse_url, request_add_authorization_header, request_add_custom_headers,
request_handle_response, request_set_body, request_set_timeout,
};
#[derive(Clone)]
pub struct SubCommand;
impl Command for SubCommand {
fn name(&self) -> &str {
"http put"
}
fn signature(&self) -> Signature {
Signature::build("http put")
.input_output_types(vec![(Type::Nothing, Type::Any)])
.allow_variants_without_examples(true)
.required("URL", SyntaxShape::String, "the URL to post to")
.required("data", SyntaxShape::Any, "the contents of the post body")
.named(
"user",
SyntaxShape::Any,
"the username when authenticating",
Some('u'),
)
.named(
"password",
SyntaxShape::Any,
"the password when authenticating",
Some('p'),
)
.named(
"content-type",
SyntaxShape::Any,
"the MIME type of content to post",
Some('t'),
)
.named(
"content-length",
SyntaxShape::Any,
"the length of the content being posted",
Some('l'),
)
.named(
"max-time",
SyntaxShape::Int,
"timeout period in seconds",
Some('m'),
)
.named(
"headers",
SyntaxShape::Any,
"custom headers you want to add ",
Some('H'),
)
.switch(
"raw",
"return values as a string instead of a table",
Some('r'),
)
.switch(
"insecure",
"allow insecure server connections when using SSL",
Some('k'),
)
.filter()
.category(Category::Network)
}
fn usage(&self) -> &str {
"Put a body to a URL."
}
fn extra_usage(&self) -> &str {
"Performs HTTP PUT operation."
}
fn search_terms(&self) -> Vec<&str> {
vec!["network", "send", "push"]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
run_put(engine_state, stack, call, input)
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Put content to example.com",
example: "http put https://www.example.com 'body'",
result: None,
},
Example {
description: "Put content to example.com, with username and password",
example: "http put -u myuser -p mypass https://www.example.com 'body'",
result: None,
},
Example {
description: "Put content to example.com, with custom header",
example: "http put -H [my-header-key my-header-value] https://www.example.com",
result: None,
},
Example {
description: "Put content to example.com, with JSON body",
example: "http put -t application/json https://www.example.com { field: value }",
result: None,
},
]
}
}
struct Arguments {
url: Value,
headers: Option<Value>,
data: Value,
content_type: Option<String>,
content_length: Option<String>,
raw: bool,
insecure: Option<bool>,
user: Option<String>,
password: Option<String>,
timeout: Option<Value>,
}
fn run_put(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let args = Arguments {
url: call.req(engine_state, stack, 0)?,
headers: call.get_flag(engine_state, stack, "headers")?,
data: call.req(engine_state, stack, 1)?,
content_type: call.get_flag(engine_state, stack, "content-type")?,
content_length: call.get_flag(engine_state, stack, "content-length")?,
raw: call.has_flag("raw"),
insecure: call.get_flag(engine_state, stack, "insecure")?,
user: call.get_flag(engine_state, stack, "user")?,
password: call.get_flag(engine_state, stack, "password")?,
timeout: call.get_flag(engine_state, stack, "timeout")?,
};
helper(engine_state, stack, call, args)
}
// Helper function that actually goes to retrieve the resource from the url given
// The Option<String> return a possible file extension which can be used in AutoConvert commands
fn helper(
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
args: Arguments,
) -> Result<PipelineData, ShellError> {
let span = args.url.span()?;
let (requested_url, url) = http_parse_url(call, span, args.url)?;
let client = http_client(args.insecure.is_some());
let mut request = client.put(url);
request = request_set_body(args.content_type, args.content_length, args.data, request)?;
request = request_set_timeout(args.timeout, request)?;
request = request_add_authorization_header(args.user, args.password, request);
request = request_add_custom_headers(args.headers, request)?;
let response = request.send().and_then(|r| r.error_for_status());
request_handle_response(
engine_state,
stack,
span,
&requested_url,
args.raw,
response,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(SubCommand {})
}
}