nu_command/network/http/
delete.rs

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