http post --content-type should set Content-Type header (#9431)

Parse the data from string to json if the `--content-type
"application/json"` flag is used for the request.

Fixes: https://github.com/nushell/nushell/issues/9408

In the issue, the actual data is a string `'{ "query": "{ greeting }"
}'` representing json, and it would match the case `Value::String { val,
.. }`


-------------------------

The example in the issue does set the `content-type` to
`application/json` but sends the body as a string note the `'`.

```
(
::: http post
:::   -fer
:::   # -H [ "Content-Type" "application/json" ]
:::   --content-type "application/json"
:::   'http://127.0.0.1:3000/greetings/hello'
:::   '{ "query": "{ greeting }" }'
::: )
```

```
╭─────────┬───────────────────────╮
│ headers │ {record 14 fields}    │
│ body    │ {"content_type":null} │
│ status  │ 200                   │
╰─────────┴───────────────────────╯
```

If we send the same request but using actual json as the body, the
Header is set correctly.

```
(        
::: http post
:::   -fer
:::   # -H [ "Content-Type" "application/json" ]
:::   --content-type "application/json"
:::   'http://127.0.0.1:3000/greetings/hello'
:::   { "query": "{ greeting }" }
::: )
```
```

╭─────────┬─────────────────────────────────────╮
│ headers │ {record 14 fields}                  │
│ body    │ {"content_type":"application/json"} │
│ status  │ 200                                 │
╰─────────┴─────────────────────────────────────╯
```
This commit is contained in:
Anas Alkhatib 2023-06-15 07:51:35 -04:00 committed by GitHub
parent d371a78a0b
commit b072d75300
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -170,6 +170,10 @@ pub fn send_request(
Box::new(move || request.send_bytes(&val)),
ctrl_c,
),
Value::String { .. } if body_type == BodyType::Json => {
let data = value_to_json_value(&body)?;
send_cancellable_request(&request_url, Box::new(|| request.send_json(data)), ctrl_c)
}
Value::String { val, .. } => send_cancellable_request(
&request_url,
Box::new(move || request.send_string(&val)),