Skip to main content

nu_command/network/http/
put.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::*;
8use nu_protocol::shell_error::generic::GenericError;
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        "Send a PUT request to a URL with a request body."
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::Generic(GenericError::new(
191            "Data must be provided either through pipeline or positional argument",
192            "",
193            call.head,
194        )));
195    };
196
197    let content_type = call
198        .get_flag(engine_state, stack, "content-type")?
199        .or_else(|| maybe_metadata.and_then(|m| m.content_type));
200
201    let args = Arguments {
202        url: call.req(engine_state, stack, 0)?,
203        headers: call.get_flag(engine_state, stack, "headers")?,
204        data,
205        content_type,
206        raw: call.has_flag(engine_state, stack, "raw")?,
207        insecure: call.has_flag(engine_state, stack, "insecure")?,
208        user: call.get_flag(engine_state, stack, "user")?,
209        password: call.get_flag(engine_state, stack, "password")?,
210        timeout: call.get_flag(engine_state, stack, "max-time")?,
211        full: call.has_flag(engine_state, stack, "full")?,
212        allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
213        redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
214        unix_socket: call.get_flag(engine_state, stack, "unix-socket")?,
215        pool: call.has_flag(engine_state, stack, "pool")?,
216    };
217
218    helper(engine_state, stack, call, args)
219}
220
221// Helper function that actually goes to retrieve the resource from the url given
222// The Option<String> return a possible file extension which can be used in AutoConvert commands
223fn helper(
224    engine_state: &EngineState,
225    stack: &mut Stack,
226    call: &Call,
227    args: Arguments,
228) -> Result<PipelineData, ShellError> {
229    let span = args.url.span();
230    let Spanned {
231        item: (requested_url, _),
232        span: request_span,
233    } = http_parse_url(call, span, args.url)?;
234    let redirect_mode = http_parse_redirect_mode(args.redirect)?;
235
236    let cwd = engine_state.cwd(None)?;
237    let unix_socket_path = expand_unix_socket_path(args.unix_socket, &cwd);
238
239    let mut request = if args.pool {
240        http_client_pool(engine_state, stack)?.put(&requested_url)
241    } else {
242        let client = http_client(
243            args.insecure,
244            redirect_mode,
245            unix_socket_path,
246            engine_state,
247            stack,
248        )?;
249        client.put(&requested_url)
250    };
251
252    request = request_set_timeout(args.timeout, request)?;
253    request = request_add_authorization_header(args.user, args.password, request);
254    request = request_add_custom_headers(args.headers, request)?;
255
256    let (response, request_headers) = send_request(
257        engine_state,
258        request,
259        request_span,
260        args.data,
261        args.content_type,
262        call.head,
263        engine_state.signals(),
264    );
265
266    let request_flags = RequestFlags {
267        raw: args.raw,
268        full: args.full,
269        allow_errors: args.allow_errors,
270    };
271    let response = response?;
272
273    check_response_redirection(redirect_mode, span, &response)?;
274    request_handle_response(
275        engine_state,
276        stack,
277        RequestMetadata {
278            requested_url: &requested_url,
279            span,
280            headers: request_headers,
281            redirect_mode,
282            flags: request_flags,
283        },
284        response,
285    )
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    #[test]
293    fn test_examples() -> nu_test_support::Result {
294        nu_test_support::test().examples(HttpPut)
295    }
296}