nu_command/network/http/
post.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,
7};
8use nu_engine::command_prelude::*;
9
10#[derive(Clone)]
11pub struct HttpPost;
12
13impl Command for HttpPost {
14    fn name(&self) -> &str {
15        "http post"
16    }
17
18    fn signature(&self) -> Signature {
19        let sig = Signature::build("http post")
20            .input_output_types(vec![(Type::Any, Type::Any)])
21            .allow_variants_without_examples(true)
22            .required("URL", SyntaxShape::String, "The URL to post to.")
23            .optional(
24                "data",
25                SyntaxShape::Any,
26                "The contents of the post body. Required unless part of a pipeline.",
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(
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                "return values as a string instead of 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(nu_protocol::Completion::new_list(
88                        super::client::RedirectMode::MODES,
89                    )),
90            )
91            .filter()
92            .category(Category::Network);
93
94        add_unix_socket_flag(sig)
95    }
96
97    fn description(&self) -> &str {
98        "Post a body to a URL."
99    }
100
101    fn extra_description(&self) -> &str {
102        "Performs HTTP POST operation."
103    }
104
105    fn search_terms(&self) -> Vec<&str> {
106        vec!["network", "send", "push"]
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_post(engine_state, stack, call, input)
117    }
118
119    fn examples(&self) -> Vec<Example<'_>> {
120        vec![
121            Example {
122                description: "Post content to example.com",
123                example: "http post https://www.example.com 'body'",
124                result: None,
125            },
126            Example {
127                description: "Post content to example.com, with username and password",
128                example: "http post --user myuser --password mypass https://www.example.com 'body'",
129                result: None,
130            },
131            Example {
132                description: "Post content to example.com, with custom header using a record",
133                example: "http post --headers {my-header-key: my-header-value} https://www.example.com",
134                result: None,
135            },
136            Example {
137                description: "Post content to example.com, with custom header using a list",
138                example: "http post --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: "Post content to example.com, with JSON body",
143                example: "http post --content-type application/json https://www.example.com { field: value }",
144                result: None,
145            },
146            Example {
147                description: "Post JSON content from a pipeline to example.com",
148                example: "open --raw foo.json | http post https://www.example.com",
149                result: None,
150            },
151            Example {
152                description: "Upload a binary file to example.com",
153                example: "http post --content-type multipart/form-data https://www.example.com { file: (open -r file.mp3) }",
154                result: None,
155            },
156            Example {
157                description: "Convert a text file into binary and upload it to example.com",
158                example: "http post --content-type multipart/form-data https://www.example.com { file: (open -r file.txt | into binary) }",
159                result: None,
160            },
161            Example {
162                description: "Get the response status code",
163                example: r#"http post https://www.example.com 'body' | metadata | get http_response.status"#,
164                result: None,
165            },
166            Example {
167                description: "Check response status while streaming",
168                example: r#"http post --allow-errors https://example.com/upload 'data' | metadata access {|m| if $m.http_response.status != 200 { error make {msg: "failed"} } else { } } | lines"#,
169                result: None,
170            },
171        ]
172    }
173}
174
175struct Arguments {
176    url: Value,
177    headers: Option<Value>,
178    data: HttpBody,
179    content_type: Option<String>,
180    raw: bool,
181    insecure: bool,
182    user: Option<String>,
183    password: Option<String>,
184    timeout: Option<Value>,
185    full: bool,
186    allow_errors: bool,
187    redirect: Option<Spanned<String>>,
188    unix_socket: Option<Spanned<String>>,
189    pool: bool,
190}
191
192pub fn run_post(
193    engine_state: &EngineState,
194    stack: &mut Stack,
195    call: &Call,
196    input: PipelineData,
197) -> Result<PipelineData, ShellError> {
198    let (data, maybe_metadata) = call
199        .opt::<Value>(engine_state, stack, 1)?
200        .map(|v| (Some(HttpBody::Value(v)), None))
201        .unwrap_or_else(|| match input {
202            PipelineData::Value(v, metadata) => (Some(HttpBody::Value(v)), metadata),
203            PipelineData::ByteStream(byte_stream, metadata) => {
204                (Some(HttpBody::ByteStream(byte_stream)), metadata)
205            }
206            _ => (None, None),
207        });
208    let content_type = call
209        .get_flag(engine_state, stack, "content-type")?
210        .or_else(|| maybe_metadata.and_then(|m| m.content_type));
211
212    let Some(data) = data else {
213        return Err(ShellError::GenericError {
214            error: "Data must be provided either through pipeline or positional argument".into(),
215            msg: "".into(),
216            span: Some(call.head),
217            help: None,
218            inner: vec![],
219        });
220    };
221
222    let args = Arguments {
223        url: call.req(engine_state, stack, 0)?,
224        headers: call.get_flag(engine_state, stack, "headers")?,
225        data,
226        content_type,
227        raw: call.has_flag(engine_state, stack, "raw")?,
228        insecure: call.has_flag(engine_state, stack, "insecure")?,
229        user: call.get_flag(engine_state, stack, "user")?,
230        password: call.get_flag(engine_state, stack, "password")?,
231        timeout: call.get_flag(engine_state, stack, "max-time")?,
232        full: call.has_flag(engine_state, stack, "full")?,
233        allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
234        redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
235        unix_socket: call.get_flag(engine_state, stack, "unix-socket")?,
236        pool: call.has_flag(engine_state, stack, "pool")?,
237    };
238
239    helper(engine_state, stack, call, args)
240}
241
242// Helper function that actually goes to retrieve the resource from the url given
243// The Option<String> return a possible file extension which can be used in AutoConvert commands
244fn helper(
245    engine_state: &EngineState,
246    stack: &mut Stack,
247    call: &Call,
248    args: Arguments,
249) -> Result<PipelineData, ShellError> {
250    let span = args.url.span();
251    let Spanned {
252        item: (requested_url, _),
253        span: request_span,
254    } = http_parse_url(call, span, args.url)?;
255    let redirect_mode = http_parse_redirect_mode(args.redirect)?;
256
257    let cwd = engine_state.cwd(None)?;
258    let unix_socket_path = expand_unix_socket_path(args.unix_socket, &cwd);
259
260    let mut request = if args.pool {
261        http_client_pool(engine_state, stack).post(&requested_url)
262    } else {
263        let client = http_client(
264            args.insecure,
265            redirect_mode,
266            unix_socket_path,
267            engine_state,
268            stack,
269        )?;
270        client.post(&requested_url)
271    };
272
273    request = request_set_timeout(args.timeout, request)?;
274    request = request_add_authorization_header(args.user, args.password, request);
275    request = request_add_custom_headers(args.headers, request)?;
276
277    let (response, request_headers) = send_request(
278        engine_state,
279        request,
280        request_span,
281        args.data,
282        args.content_type,
283        call.head,
284        engine_state.signals(),
285    );
286
287    let request_flags = RequestFlags {
288        raw: args.raw,
289        full: args.full,
290        allow_errors: args.allow_errors,
291    };
292
293    let response = response?;
294
295    check_response_redirection(redirect_mode, span, &response)?;
296    request_handle_response(
297        engine_state,
298        stack,
299        RequestMetadata {
300            requested_url: &requested_url,
301            span,
302            headers: request_headers,
303            redirect_mode,
304            flags: request_flags,
305        },
306        response,
307    )
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    #[test]
315    fn test_examples() {
316        use crate::test_examples;
317
318        test_examples(HttpPost {})
319    }
320}