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