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