1use crate::network::http::client::{
2 HttpBody, RequestFlags, RequestMetadata, check_response_redirection, http_client,
3 http_parse_redirect_mode, http_parse_url, request_add_authorization_header,
4 request_add_custom_headers, request_handle_response, request_set_timeout, send_request,
5 send_request_no_body,
6};
7use nu_engine::command_prelude::*;
8
9use super::client::RedirectMode;
10
11#[derive(Clone)]
12pub struct HttpDelete;
13
14impl Command for HttpDelete {
15 fn name(&self) -> &str {
16 "http delete"
17 }
18
19 fn signature(&self) -> Signature {
20 Signature::build("http delete")
21 .input_output_types(vec![(Type::Any, Type::Any)])
22 .allow_variants_without_examples(true)
23 .required(
24 "URL",
25 SyntaxShape::String,
26 "The URL to fetch the contents from.",
27 )
28 .named(
29 "user",
30 SyntaxShape::Any,
31 "the username when authenticating",
32 Some('u'),
33 )
34 .named(
35 "password",
36 SyntaxShape::Any,
37 "the password when authenticating",
38 Some('p'),
39 )
40 .named("data", SyntaxShape::Any, "the content to post", Some('d'))
41 .named(
42 "content-type",
43 SyntaxShape::Any,
44 "the MIME type of content to post",
45 Some('t'),
46 )
47 .named(
48 "max-time",
49 SyntaxShape::Duration,
50 "max duration before timeout occurs",
51 Some('m'),
52 )
53 .named(
54 "headers",
55 SyntaxShape::Any,
56 "custom headers you want to add ",
57 Some('H'),
58 )
59 .switch(
60 "raw",
61 "fetch contents as text rather than a table",
62 Some('r'),
63 )
64 .switch(
65 "insecure",
66 "allow insecure server connections when using SSL",
67 Some('k'),
68 )
69 .switch(
70 "full",
71 "returns the full response instead of only the body",
72 Some('f'),
73 )
74 .switch(
75 "allow-errors",
76 "do not fail if the server returns an error code",
77 Some('e'),
78 )
79 .param(
80 Flag::new("redirect-mode")
81 .short('R')
82 .arg(SyntaxShape::String)
83 .desc(
84 "What to do when encountering redirects. Default: 'follow'. Valid \
85 options: 'follow' ('f'), 'manual' ('m'), 'error' ('e').",
86 )
87 .completion(Completion::new_list(RedirectMode::MODES)),
88 )
89 .filter()
90 .category(Category::Network)
91 }
92
93 fn description(&self) -> &str {
94 "Delete the specified resource."
95 }
96
97 fn extra_description(&self) -> &str {
98 "Performs HTTP DELETE operation."
99 }
100
101 fn search_terms(&self) -> Vec<&str> {
102 vec!["network", "request", "curl", "wget"]
103 }
104
105 fn run(
106 &self,
107 engine_state: &EngineState,
108 stack: &mut Stack,
109 call: &Call,
110 input: PipelineData,
111 ) -> Result<PipelineData, ShellError> {
112 run_delete(engine_state, stack, call, input)
113 }
114
115 fn examples(&self) -> Vec<Example<'_>> {
116 vec![
117 Example {
118 description: "http delete from example.com",
119 example: "http delete https://www.example.com",
120 result: None,
121 },
122 Example {
123 description: "http delete from example.com, with username and password",
124 example: "http delete --user myuser --password mypass https://www.example.com",
125 result: None,
126 },
127 Example {
128 description: "http delete from example.com, with custom header using a record",
129 example: "http delete --headers {my-header-key: my-header-value} https://www.example.com",
130 result: None,
131 },
132 Example {
133 description: "http delete from example.com, with custom header using a list",
134 example: "http delete --headers [my-header-key-A my-header-value-A my-header-key-B my-header-value-B] https://www.example.com",
135 result: None,
136 },
137 Example {
138 description: "http delete from example.com, with body",
139 example: "http delete --data 'body' https://www.example.com",
140 result: None,
141 },
142 Example {
143 description: "http delete from example.com, with JSON body",
144 example: "http delete --content-type application/json --data { field: value } https://www.example.com",
145 result: None,
146 },
147 Example {
148 description: "Perform an HTTP delete with JSON content from a pipeline to example.com",
149 example: "open foo.json | http delete https://www.example.com",
150 result: None,
151 },
152 ]
153 }
154}
155
156struct Arguments {
157 url: Value,
158 headers: Option<Value>,
159 data: Option<HttpBody>,
160 content_type: Option<String>,
161 raw: bool,
162 insecure: bool,
163 user: Option<String>,
164 password: Option<String>,
165 timeout: Option<Value>,
166 full: bool,
167 allow_errors: bool,
168 redirect: Option<Spanned<String>>,
169}
170
171fn run_delete(
172 engine_state: &EngineState,
173 stack: &mut Stack,
174 call: &Call,
175 input: PipelineData,
176) -> Result<PipelineData, ShellError> {
177 let (data, maybe_metadata) = call
178 .get_flag::<Value>(engine_state, stack, "data")?
179 .map(|v| (Some(HttpBody::Value(v)), None))
180 .unwrap_or_else(|| match input {
181 PipelineData::Value(v, metadata) => (Some(HttpBody::Value(v)), metadata),
182 PipelineData::ByteStream(byte_stream, metadata) => {
183 (Some(HttpBody::ByteStream(byte_stream)), metadata)
184 }
185 _ => (None, None),
186 });
187 let content_type = call
188 .get_flag(engine_state, stack, "content-type")?
189 .or_else(|| maybe_metadata.and_then(|m| m.content_type));
190
191 let args = Arguments {
192 url: call.req(engine_state, stack, 0)?,
193 headers: call.get_flag(engine_state, stack, "headers")?,
194 data,
195 content_type,
196 raw: call.has_flag(engine_state, stack, "raw")?,
197 insecure: call.has_flag(engine_state, stack, "insecure")?,
198 user: call.get_flag(engine_state, stack, "user")?,
199 password: call.get_flag(engine_state, stack, "password")?,
200 timeout: call.get_flag(engine_state, stack, "max-time")?,
201 full: call.has_flag(engine_state, stack, "full")?,
202 allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
203 redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
204 };
205
206 helper(engine_state, stack, call, args)
207}
208
209fn helper(
212 engine_state: &EngineState,
213 stack: &mut Stack,
214 call: &Call,
215 args: Arguments,
216) -> Result<PipelineData, ShellError> {
217 let span = args.url.span();
218 let (requested_url, _) = http_parse_url(call, span, args.url)?;
219 let redirect_mode = http_parse_redirect_mode(args.redirect)?;
220
221 let client = http_client(args.insecure, redirect_mode, engine_state, stack)?;
222 let mut request = client.delete(&requested_url);
223
224 request = request_set_timeout(args.timeout, request)?;
225 request = request_add_authorization_header(args.user, args.password, request);
226 request = request_add_custom_headers(args.headers, request)?;
227 let (response, request_headers) = match args.data {
228 None => send_request_no_body(request, call.head, engine_state.signals()),
229
230 Some(body) => send_request(
231 engine_state,
232 request.force_send_body(),
238 body,
239 args.content_type,
240 span,
241 engine_state.signals(),
242 ),
243 };
244
245 let request_flags = RequestFlags {
246 raw: args.raw,
247 full: args.full,
248 allow_errors: args.allow_errors,
249 };
250 let response = response?;
251
252 check_response_redirection(redirect_mode, span, &response)?;
253 request_handle_response(
254 engine_state,
255 stack,
256 RequestMetadata {
257 requested_url: &requested_url,
258 span,
259 headers: request_headers,
260 redirect_mode,
261 flags: request_flags,
262 },
263 response,
264 )
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[test]
272 fn test_examples() {
273 use crate::test_examples;
274
275 test_examples(HttpDelete {})
276 }
277}