nu_command/network/http/
put.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 HttpPut;
10
11impl Command for HttpPut {
12    fn name(&self) -> &str {
13        "http put"
14    }
15
16    fn signature(&self) -> Signature {
17        Signature::build("http put")
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        "Put a body to a URL."
83    }
84
85    fn extra_description(&self) -> &str {
86        "Performs HTTP PUT 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_put(engine_state, stack, call, input)
101    }
102
103    fn examples(&self) -> Vec<Example> {
104        vec![
105            Example {
106                description: "Put content to example.com",
107                example: "http put https://www.example.com 'body'",
108                result: None,
109            },
110            Example {
111                description: "Put content to example.com, with username and password",
112                example: "http put --user myuser --password mypass https://www.example.com 'body'",
113                result: None,
114            },
115            Example {
116                description: "Put content to example.com, with custom header using a record",
117                example: "http put --headers {my-header-key: my-header-value} https://www.example.com",
118                result: None,
119            },
120            Example {
121                description: "Put content to example.com, with custom header using a list",
122                example: "http put --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: "Put content to example.com, with JSON body",
127                example: "http put --content-type application/json https://www.example.com { field: value }",
128                result: None,
129            },
130            Example {
131                description: "Put JSON content from a pipeline to example.com",
132                example: "open --raw foo.json | http put https://www.example.com",
133                result: None,
134            },
135        ]
136    }
137}
138
139struct Arguments {
140    url: Value,
141    headers: Option<Value>,
142    data: HttpBody,
143    content_type: Option<String>,
144    raw: bool,
145    insecure: bool,
146    user: Option<String>,
147    password: Option<String>,
148    timeout: Option<Value>,
149    full: bool,
150    allow_errors: bool,
151    redirect: Option<Spanned<String>>,
152}
153
154fn run_put(
155    engine_state: &EngineState,
156    stack: &mut Stack,
157    call: &Call,
158    input: PipelineData,
159) -> Result<PipelineData, ShellError> {
160    let (data, maybe_metadata) = call
161        .opt::<Value>(engine_state, stack, 1)?
162        .map(|v| (HttpBody::Value(v), None))
163        .unwrap_or_else(|| match input {
164            PipelineData::Value(v, metadata) => (HttpBody::Value(v), metadata),
165            PipelineData::ByteStream(byte_stream, metadata) => {
166                (HttpBody::ByteStream(byte_stream), metadata)
167            }
168            _ => (HttpBody::None, None),
169        });
170
171    if let HttpBody::None = data {
172        return Err(ShellError::GenericError {
173            error: "Data must be provided either through pipeline or positional argument".into(),
174            msg: "".into(),
175            span: Some(call.head),
176            help: None,
177            inner: vec![],
178        });
179    }
180
181    let content_type = call
182        .get_flag(engine_state, stack, "content-type")?
183        .or_else(|| maybe_metadata.and_then(|m| m.content_type));
184
185    let args = Arguments {
186        url: call.req(engine_state, stack, 0)?,
187        headers: call.get_flag(engine_state, stack, "headers")?,
188        data,
189        content_type,
190        raw: call.has_flag(engine_state, stack, "raw")?,
191        insecure: call.has_flag(engine_state, stack, "insecure")?,
192        user: call.get_flag(engine_state, stack, "user")?,
193        password: call.get_flag(engine_state, stack, "password")?,
194        timeout: call.get_flag(engine_state, stack, "max-time")?,
195        full: call.has_flag(engine_state, stack, "full")?,
196        allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
197        redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
198    };
199
200    helper(engine_state, stack, call, args)
201}
202
203// Helper function that actually goes to retrieve the resource from the url given
204// The Option<String> return a possible file extension which can be used in AutoConvert commands
205fn helper(
206    engine_state: &EngineState,
207    stack: &mut Stack,
208    call: &Call,
209    args: Arguments,
210) -> Result<PipelineData, ShellError> {
211    let span = args.url.span();
212    let (requested_url, _) = http_parse_url(call, span, args.url)?;
213    let redirect_mode = http_parse_redirect_mode(args.redirect)?;
214
215    let client = http_client(args.insecure, redirect_mode, engine_state, stack)?;
216    let mut request = client.put(&requested_url);
217
218    request = request_set_timeout(args.timeout, request)?;
219    request = request_add_authorization_header(args.user, args.password, request);
220    request = request_add_custom_headers(args.headers, request)?;
221
222    let response = send_request(
223        engine_state,
224        request.clone(),
225        args.data,
226        args.content_type,
227        call.head,
228        engine_state.signals(),
229    );
230
231    let request_flags = RequestFlags {
232        raw: args.raw,
233        full: args.full,
234        allow_errors: args.allow_errors,
235    };
236
237    check_response_redirection(redirect_mode, span, &response)?;
238    request_handle_response(
239        engine_state,
240        stack,
241        span,
242        &requested_url,
243        request_flags,
244        response,
245        request,
246    )
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn test_examples() {
255        use crate::test_examples;
256
257        test_examples(HttpPut {})
258    }
259}