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