1use crate::network::http::client::{
2 HttpBody, RequestFlags, RequestMetadata, check_response_redirection, http_client,
3 http_parse_redirect_mode, http_parse_url, request_add_authorization_header,
4 request_add_custom_headers, 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(
22 "data",
23 SyntaxShape::Any,
24 "The contents of the post body. Required unless part of a pipeline.",
25 )
26 .named(
27 "user",
28 SyntaxShape::Any,
29 "the username when authenticating",
30 Some('u'),
31 )
32 .named(
33 "password",
34 SyntaxShape::Any,
35 "the password when authenticating",
36 Some('p'),
37 )
38 .named(
39 "content-type",
40 SyntaxShape::Any,
41 "the MIME type of content to post",
42 Some('t'),
43 )
44 .named(
45 "max-time",
46 SyntaxShape::Duration,
47 "max duration before timeout occurs",
48 Some('m'),
49 )
50 .named(
51 "headers",
52 SyntaxShape::Any,
53 "custom headers you want to add ",
54 Some('H'),
55 )
56 .switch(
57 "raw",
58 "return values as a string instead of a table",
59 Some('r'),
60 )
61 .switch(
62 "insecure",
63 "allow insecure server connections when using SSL",
64 Some('k'),
65 )
66 .switch(
67 "full",
68 "returns the full response instead of only the body",
69 Some('f'),
70 )
71 .switch(
72 "allow-errors",
73 "do not fail if the server returns an error code",
74 Some('e'),
75 )
76 .param(
77 Flag::new("redirect-mode")
78 .short('R')
79 .arg(SyntaxShape::String)
80 .desc(
81 "What to do when encountering redirects. Default: 'follow'. Valid \
82 options: 'follow' ('f'), 'manual' ('m'), 'error' ('e').",
83 )
84 .completion(nu_protocol::Completion::new_list(
85 super::client::RedirectMode::MODES,
86 )),
87 )
88 .filter()
89 .category(Category::Network)
90 }
91
92 fn description(&self) -> &str {
93 "Put a body to a URL."
94 }
95
96 fn extra_description(&self) -> &str {
97 "Performs HTTP PUT operation."
98 }
99
100 fn search_terms(&self) -> Vec<&str> {
101 vec!["network", "send", "push"]
102 }
103
104 fn run(
105 &self,
106 engine_state: &EngineState,
107 stack: &mut Stack,
108 call: &Call,
109 input: PipelineData,
110 ) -> Result<PipelineData, ShellError> {
111 run_put(engine_state, stack, call, input)
112 }
113
114 fn examples(&self) -> Vec<Example<'_>> {
115 vec![
116 Example {
117 description: "Put content to example.com",
118 example: "http put https://www.example.com 'body'",
119 result: None,
120 },
121 Example {
122 description: "Put content to example.com, with username and password",
123 example: "http put --user myuser --password mypass https://www.example.com 'body'",
124 result: None,
125 },
126 Example {
127 description: "Put content to example.com, with custom header using a record",
128 example: "http put --headers {my-header-key: my-header-value} https://www.example.com",
129 result: None,
130 },
131 Example {
132 description: "Put content to example.com, with custom header using a list",
133 example: "http put --headers [my-header-key-A my-header-value-A my-header-key-B my-header-value-B] https://www.example.com",
134 result: None,
135 },
136 Example {
137 description: "Put content to example.com, with JSON body",
138 example: "http put --content-type application/json https://www.example.com { field: value }",
139 result: None,
140 },
141 Example {
142 description: "Put JSON content from a pipeline to example.com",
143 example: "open --raw foo.json | http put https://www.example.com",
144 result: None,
145 },
146 ]
147 }
148}
149
150struct Arguments {
151 url: Value,
152 headers: Option<Value>,
153 data: HttpBody,
154 content_type: Option<String>,
155 raw: bool,
156 insecure: bool,
157 user: Option<String>,
158 password: Option<String>,
159 timeout: Option<Value>,
160 full: bool,
161 allow_errors: bool,
162 redirect: Option<Spanned<String>>,
163}
164
165fn run_put(
166 engine_state: &EngineState,
167 stack: &mut Stack,
168 call: &Call,
169 input: PipelineData,
170) -> Result<PipelineData, ShellError> {
171 let (data, maybe_metadata) = call
172 .opt::<Value>(engine_state, stack, 1)?
173 .map(|v| (Some(HttpBody::Value(v)), None))
174 .unwrap_or_else(|| match input {
175 PipelineData::Value(v, metadata) => (Some(HttpBody::Value(v)), metadata),
176 PipelineData::ByteStream(byte_stream, metadata) => {
177 (Some(HttpBody::ByteStream(byte_stream)), metadata)
178 }
179 _ => (None, None),
180 });
181
182 let Some(data) = data else {
183 return Err(ShellError::GenericError {
184 error: "Data must be provided either through pipeline or positional argument".into(),
185 msg: "".into(),
186 span: Some(call.head),
187 help: None,
188 inner: vec![],
189 });
190 };
191
192 let content_type = call
193 .get_flag(engine_state, stack, "content-type")?
194 .or_else(|| maybe_metadata.and_then(|m| m.content_type));
195
196 let args = Arguments {
197 url: call.req(engine_state, stack, 0)?,
198 headers: call.get_flag(engine_state, stack, "headers")?,
199 data,
200 content_type,
201 raw: call.has_flag(engine_state, stack, "raw")?,
202 insecure: call.has_flag(engine_state, stack, "insecure")?,
203 user: call.get_flag(engine_state, stack, "user")?,
204 password: call.get_flag(engine_state, stack, "password")?,
205 timeout: call.get_flag(engine_state, stack, "max-time")?,
206 full: call.has_flag(engine_state, stack, "full")?,
207 allow_errors: call.has_flag(engine_state, stack, "allow-errors")?,
208 redirect: call.get_flag(engine_state, stack, "redirect-mode")?,
209 };
210
211 helper(engine_state, stack, call, args)
212}
213
214fn helper(
217 engine_state: &EngineState,
218 stack: &mut Stack,
219 call: &Call,
220 args: Arguments,
221) -> Result<PipelineData, ShellError> {
222 let span = args.url.span();
223 let (requested_url, _) = http_parse_url(call, span, args.url)?;
224 let redirect_mode = http_parse_redirect_mode(args.redirect)?;
225
226 let client = http_client(args.insecure, redirect_mode, engine_state, stack)?;
227 let mut request = client.put(&requested_url);
228
229 request = request_set_timeout(args.timeout, request)?;
230 request = request_add_authorization_header(args.user, args.password, request);
231 request = request_add_custom_headers(args.headers, request)?;
232
233 let (response, request_headers) = send_request(
234 engine_state,
235 request,
236 args.data,
237 args.content_type,
238 call.head,
239 engine_state.signals(),
240 );
241
242 let request_flags = RequestFlags {
243 raw: args.raw,
244 full: args.full,
245 allow_errors: args.allow_errors,
246 };
247 let response = response?;
248
249 check_response_redirection(redirect_mode, span, &response)?;
250 request_handle_response(
251 engine_state,
252 stack,
253 RequestMetadata {
254 requested_url: &requested_url,
255 span,
256 headers: request_headers,
257 redirect_mode,
258 flags: request_flags,
259 },
260 response,
261 )
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267
268 #[test]
269 fn test_examples() {
270 use crate::test_examples;
271
272 test_examples(HttpPut {})
273 }
274}