nu_command/network/http/
post.rs

1use crate::network::http::client::{
2    HttpBody, RequestFlags, check_response_redirection, http_client, http_parse_redirect_mode,
3    http_parse_url, request_add_authorization_header, request_add_custom_headers,
4    request_handle_response, request_set_timeout, send_request,
5};
6use nu_engine::command_prelude::*;
7
8#[derive(Clone)]
9pub struct HttpPost;
10
11impl Command for HttpPost {
12    fn name(&self) -> &str {
13        "http post"
14    }
15
16    fn signature(&self) -> Signature {
17        Signature::build("http post")
18            .input_output_types(vec![(Type::Any, Type::Any)])
19            .allow_variants_without_examples(true)
20            .required("URL", SyntaxShape::String, "The URL to post to.")
21            .optional("data", SyntaxShape::Any, "The contents of the post body. Required unless part of a pipeline.")
22            .named(
23                "user",
24                SyntaxShape::Any,
25                "the username when authenticating",
26                Some('u'),
27            )
28            .named(
29                "password",
30                SyntaxShape::Any,
31                "the password when authenticating",
32                Some('p'),
33            )
34            .named(
35                "content-type",
36                SyntaxShape::Any,
37                "the MIME type of content to post",
38                Some('t'),
39            )
40            .named(
41                "max-time",
42                SyntaxShape::Duration,
43                "max duration before timeout occurs",
44                Some('m'),
45            )
46            .named(
47                "headers",
48                SyntaxShape::Any,
49                "custom headers you want to add ",
50                Some('H'),
51            )
52            .switch(
53                "raw",
54                "return values as a string instead of a table",
55                Some('r'),
56            )
57            .switch(
58                "insecure",
59                "allow insecure server connections when using SSL",
60                Some('k'),
61            )
62            .switch(
63                "full",
64                "returns the full response instead of only the body",
65                Some('f'),
66            )
67            .switch(
68                "allow-errors",
69                "do not fail if the server returns an error code",
70                Some('e'),
71            ).named(
72                "redirect-mode",
73                SyntaxShape::String,
74                "What to do when encountering redirects. Default: 'follow'. Valid options: 'follow' ('f'), 'manual' ('m'), 'error' ('e').",
75                Some('R')
76            )
77            .filter()
78            .category(Category::Network)
79    }
80
81    fn description(&self) -> &str {
82        "Post a body to a URL."
83    }
84
85    fn extra_description(&self) -> &str {
86        "Performs HTTP POST operation."
87    }
88
89    fn search_terms(&self) -> Vec<&str> {
90        vec!["network", "send", "push"]
91    }
92
93    fn run(
94        &self,
95        engine_state: &EngineState,
96        stack: &mut Stack,
97        call: &Call,
98        input: PipelineData,
99    ) -> Result<PipelineData, ShellError> {
100        run_post(engine_state, stack, call, input)
101    }
102
103    fn examples(&self) -> Vec<Example> {
104        vec![
105            Example {
106                description: "Post content to example.com",
107                example: "http post https://www.example.com 'body'",
108                result: None,
109            },
110            Example {
111                description: "Post content to example.com, with username and password",
112                example: "http post --user myuser --password mypass https://www.example.com 'body'",
113                result: None,
114            },
115            Example {
116                description: "Post content to example.com, with custom header using a record",
117                example: "http post --headers {my-header-key: my-header-value} https://www.example.com",
118                result: None,
119            },
120            Example {
121                description: "Post content to example.com, with custom header using a list",
122                example: "http post --headers [my-header-key-A my-header-value-A my-header-key-B my-header-value-B] https://www.example.com",
123                result: None,
124            },
125            Example {
126                description: "Post content to example.com, with JSON body",
127                example: "http post --content-type application/json https://www.example.com { field: value }",
128                result: None,
129            },
130            Example {
131                description: "Post JSON content from a pipeline to example.com",
132                example: "open --raw foo.json | http post https://www.example.com",
133                result: None,
134            },
135            Example {
136                description: "Upload a binary file to example.com",
137                example: "http post --content-type multipart/form-data https://www.example.com { file: (open -r file.mp3) }",
138                result: None,
139            },
140            Example {
141                description: "Convert a text file into binary and upload it to example.com",
142                example: "http post --content-type multipart/form-data https://www.example.com { file: (open -r file.txt | into binary) }",
143                result: None,
144            },
145        ]
146    }
147}
148
149struct Arguments {
150    url: Value,
151    headers: Option<Value>,
152    data: HttpBody,
153    content_type: Option<String>,
154    raw: bool,
155    insecure: bool,
156    user: Option<String>,
157    password: Option<String>,
158    timeout: Option<Value>,
159    full: bool,
160    allow_errors: bool,
161    redirect: Option<Spanned<String>>,
162}
163
164fn run_post(
165    engine_state: &EngineState,
166    stack: &mut Stack,
167    call: &Call,
168    input: PipelineData,
169) -> Result<PipelineData, ShellError> {
170    let (data, maybe_metadata) = call
171        .opt::<Value>(engine_state, stack, 1)?
172        .map(|v| (HttpBody::Value(v), None))
173        .unwrap_or_else(|| match input {
174            PipelineData::Value(v, metadata) => (HttpBody::Value(v), metadata),
175            PipelineData::ByteStream(byte_stream, metadata) => {
176                (HttpBody::ByteStream(byte_stream), metadata)
177            }
178            _ => (HttpBody::None, None),
179        });
180    let content_type = call
181        .get_flag(engine_state, stack, "content-type")?
182        .or_else(|| maybe_metadata.and_then(|m| m.content_type));
183
184    if let HttpBody::None = data {
185        return Err(ShellError::GenericError {
186            error: "Data must be provided either through pipeline or positional argument".into(),
187            msg: "".into(),
188            span: Some(call.head),
189            help: None,
190            inner: vec![],
191        });
192    }
193
194    let args = Arguments {
195        url: call.req(engine_state, stack, 0)?,
196        headers: call.get_flag(engine_state, stack, "headers")?,
197        data,
198        content_type,
199        raw: call.has_flag(engine_state, stack, "raw")?,
200        insecure: call.has_flag(engine_state, stack, "insecure")?,
201        user: call.get_flag(engine_state, stack, "user")?,
202        password: call.get_flag(engine_state, stack, "password")?,
203        timeout: call.get_flag(engine_state, stack, "max-time")?,
204        full: call.has_flag(engine_state, stack, "full")?,
205        allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
206        redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
207    };
208
209    helper(engine_state, stack, call, args)
210}
211
212// Helper function that actually goes to retrieve the resource from the url given
213// The Option<String> return a possible file extension which can be used in AutoConvert commands
214fn helper(
215    engine_state: &EngineState,
216    stack: &mut Stack,
217    call: &Call,
218    args: Arguments,
219) -> Result<PipelineData, ShellError> {
220    let span = args.url.span();
221    let (requested_url, _) = http_parse_url(call, span, args.url)?;
222    let redirect_mode = http_parse_redirect_mode(args.redirect)?;
223
224    let client = http_client(args.insecure, redirect_mode, engine_state, stack)?;
225    let mut request = client.post(&requested_url);
226
227    request = request_set_timeout(args.timeout, request)?;
228    request = request_add_authorization_header(args.user, args.password, request);
229    request = request_add_custom_headers(args.headers, request)?;
230
231    let response = send_request(
232        engine_state,
233        request.clone(),
234        args.data,
235        args.content_type,
236        call.head,
237        engine_state.signals(),
238    );
239
240    let request_flags = RequestFlags {
241        raw: args.raw,
242        full: args.full,
243        allow_errors: args.allow_errors,
244    };
245
246    check_response_redirection(redirect_mode, span, &response)?;
247    request_handle_response(
248        engine_state,
249        stack,
250        span,
251        &requested_url,
252        request_flags,
253        response,
254        request,
255    )
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn test_examples() {
264        use crate::test_examples;
265
266        test_examples(HttpPost {})
267    }
268}