nu_command/network/http/
put.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_client_pool, http_parse_redirect_mode, http_parse_url,
5    request_add_authorization_header, request_add_custom_headers, request_handle_response,
6    request_set_timeout, send_request,
7};
8use nu_engine::command_prelude::*;
9
10#[derive(Clone)]
11pub struct HttpPut;
12
13impl Command for HttpPut {
14    fn name(&self) -> &str {
15        "http put"
16    }
17
18    fn signature(&self) -> Signature {
19        let sig = Signature::build("http put")
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        "Put a body to a URL."
99    }
100
101    fn extra_description(&self) -> &str {
102        "Performs HTTP PUT 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_put(engine_state, stack, call, input)
117    }
118
119    fn examples(&self) -> Vec<Example<'_>> {
120        vec![
121            Example {
122                description: "Put content to example.com",
123                example: "http put https://www.example.com 'body'",
124                result: None,
125            },
126            Example {
127                description: "Put content to example.com, with username and password",
128                example: "http put --user myuser --password mypass https://www.example.com 'body'",
129                result: None,
130            },
131            Example {
132                description: "Put content to example.com, with custom header using a record",
133                example: "http put --headers {my-header-key: my-header-value} https://www.example.com",
134                result: None,
135            },
136            Example {
137                description: "Put content to example.com, with custom header using a list",
138                example: "http put --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: "Put content to example.com, with JSON body",
143                example: "http put --content-type application/json https://www.example.com { field: value }",
144                result: None,
145            },
146            Example {
147                description: "Put JSON content from a pipeline to example.com",
148                example: "open --raw foo.json | http put https://www.example.com",
149                result: None,
150            },
151        ]
152    }
153}
154
155struct Arguments {
156    url: Value,
157    headers: Option<Value>,
158    data: HttpBody,
159    content_type: Option<String>,
160    raw: bool,
161    insecure: bool,
162    user: Option<String>,
163    password: Option<String>,
164    timeout: Option<Value>,
165    full: bool,
166    allow_errors: bool,
167    redirect: Option<Spanned<String>>,
168    unix_socket: Option<Spanned<String>>,
169    pool: bool,
170}
171
172fn run_put(
173    engine_state: &EngineState,
174    stack: &mut Stack,
175    call: &Call,
176    input: PipelineData,
177) -> Result<PipelineData, ShellError> {
178    let (data, maybe_metadata) = call
179        .opt::<Value>(engine_state, stack, 1)?
180        .map(|v| (Some(HttpBody::Value(v)), None))
181        .unwrap_or_else(|| match input {
182            PipelineData::Value(v, metadata) => (Some(HttpBody::Value(v)), metadata),
183            PipelineData::ByteStream(byte_stream, metadata) => {
184                (Some(HttpBody::ByteStream(byte_stream)), metadata)
185            }
186            _ => (None, None),
187        });
188
189    let Some(data) = data else {
190        return Err(ShellError::GenericError {
191            error: "Data must be provided either through pipeline or positional argument".into(),
192            msg: "".into(),
193            span: Some(call.head),
194            help: None,
195            inner: vec![],
196        });
197    };
198
199    let content_type = call
200        .get_flag(engine_state, stack, "content-type")?
201        .or_else(|| maybe_metadata.and_then(|m| m.content_type));
202
203    let args = Arguments {
204        url: call.req(engine_state, stack, 0)?,
205        headers: call.get_flag(engine_state, stack, "headers")?,
206        data,
207        content_type,
208        raw: call.has_flag(engine_state, stack, "raw")?,
209        insecure: call.has_flag(engine_state, stack, "insecure")?,
210        user: call.get_flag(engine_state, stack, "user")?,
211        password: call.get_flag(engine_state, stack, "password")?,
212        timeout: call.get_flag(engine_state, stack, "max-time")?,
213        full: call.has_flag(engine_state, stack, "full")?,
214        allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
215        redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
216        unix_socket: call.get_flag(engine_state, stack, "unix-socket")?,
217        pool: call.has_flag(engine_state, stack, "pool")?,
218    };
219
220    helper(engine_state, stack, call, args)
221}
222
223// Helper function that actually goes to retrieve the resource from the url given
224// The Option<String> return a possible file extension which can be used in AutoConvert commands
225fn helper(
226    engine_state: &EngineState,
227    stack: &mut Stack,
228    call: &Call,
229    args: Arguments,
230) -> Result<PipelineData, ShellError> {
231    let span = args.url.span();
232    let Spanned {
233        item: (requested_url, _),
234        span: request_span,
235    } = http_parse_url(call, span, args.url)?;
236    let redirect_mode = http_parse_redirect_mode(args.redirect)?;
237
238    let cwd = engine_state.cwd(None)?;
239    let unix_socket_path = expand_unix_socket_path(args.unix_socket, &cwd);
240
241    let mut request = if args.pool {
242        http_client_pool(engine_state, stack).put(&requested_url)
243    } else {
244        let client = http_client(
245            args.insecure,
246            redirect_mode,
247            unix_socket_path,
248            engine_state,
249            stack,
250        )?;
251        client.put(&requested_url)
252    };
253
254    request = request_set_timeout(args.timeout, request)?;
255    request = request_add_authorization_header(args.user, args.password, request);
256    request = request_add_custom_headers(args.headers, request)?;
257
258    let (response, request_headers) = send_request(
259        engine_state,
260        request,
261        request_span,
262        args.data,
263        args.content_type,
264        call.head,
265        engine_state.signals(),
266    );
267
268    let request_flags = RequestFlags {
269        raw: args.raw,
270        full: args.full,
271        allow_errors: args.allow_errors,
272    };
273    let response = response?;
274
275    check_response_redirection(redirect_mode, span, &response)?;
276    request_handle_response(
277        engine_state,
278        stack,
279        RequestMetadata {
280            requested_url: &requested_url,
281            span,
282            headers: request_headers,
283            redirect_mode,
284            flags: request_flags,
285        },
286        response,
287    )
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn test_examples() {
296        use crate::test_examples;
297
298        test_examples(HttpPut {})
299    }
300}