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