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