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