Skip to main content

nu_command/network/http/
post.rs

1use crate::network::http::client::{
2    HttpBody, RequestFlags, RequestMetadata, add_unix_socket_flag, check_response_redirection,
3    expand_unix_socket_path, http_client, http_client_pool, http_parse_redirect_mode,
4    http_parse_url, request_add_authorization_header, request_add_custom_headers,
5    request_handle_response, request_set_timeout, send_request,
6};
7use nu_engine::command_prelude::*;
8use nu_protocol::shell_error::generic::GenericError;
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        "Send a POST request to a URL with a request body."
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: "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::Generic(GenericError::new(
214            "Data must be provided either through pipeline or positional argument",
215            "",
216            call.head,
217        )));
218    };
219
220    let args = Arguments {
221        url: call.req(engine_state, stack, 0)?,
222        headers: call.get_flag(engine_state, stack, "headers")?,
223        data,
224        content_type,
225        raw: call.has_flag(engine_state, stack, "raw")?,
226        insecure: call.has_flag(engine_state, stack, "insecure")?,
227        user: call.get_flag(engine_state, stack, "user")?,
228        password: call.get_flag(engine_state, stack, "password")?,
229        timeout: call.get_flag(engine_state, stack, "max-time")?,
230        full: call.has_flag(engine_state, stack, "full")?,
231        allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
232        redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
233        unix_socket: call.get_flag(engine_state, stack, "unix-socket")?,
234        pool: call.has_flag(engine_state, stack, "pool")?,
235    };
236
237    helper(engine_state, stack, call, args)
238}
239
240// Helper function that actually goes to retrieve the resource from the url given
241// The Option<String> return a possible file extension which can be used in AutoConvert commands
242fn helper(
243    engine_state: &EngineState,
244    stack: &mut Stack,
245    call: &Call,
246    args: Arguments,
247) -> Result<PipelineData, ShellError> {
248    let span = args.url.span();
249    let Spanned {
250        item: (requested_url, _),
251        span: request_span,
252    } = http_parse_url(call, span, args.url)?;
253    let redirect_mode = http_parse_redirect_mode(args.redirect)?;
254
255    let cwd = engine_state.cwd(None)?;
256    let unix_socket_path = expand_unix_socket_path(args.unix_socket, &cwd);
257
258    let mut request = if args.pool {
259        http_client_pool(engine_state, stack)?.post(&requested_url)
260    } else {
261        let client = http_client(
262            args.insecure,
263            redirect_mode,
264            unix_socket_path,
265            engine_state,
266            stack,
267        )?;
268        client.post(&requested_url)
269    };
270
271    request = request_set_timeout(args.timeout, request)?;
272    request = request_add_authorization_header(args.user, args.password, request);
273    request = request_add_custom_headers(args.headers, request)?;
274
275    let (response, request_headers) = send_request(
276        engine_state,
277        request,
278        request_span,
279        args.data,
280        args.content_type,
281        call.head,
282        engine_state.signals(),
283    );
284
285    let request_flags = RequestFlags {
286        raw: args.raw,
287        full: args.full,
288        allow_errors: args.allow_errors,
289    };
290
291    let response = response?;
292
293    check_response_redirection(redirect_mode, span, &response)?;
294    request_handle_response(
295        engine_state,
296        stack,
297        RequestMetadata {
298            requested_url: &requested_url,
299            span,
300            headers: request_headers,
301            redirect_mode,
302            flags: request_flags,
303        },
304        response,
305    )
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    #[test]
313    fn test_examples() -> nu_test_support::Result {
314        nu_test_support::test().examples(HttpPost)
315    }
316}