Skip to content
Snippets Groups Projects
Commit 6a364cbc authored by Sergey Bronnikov's avatar Sergey Bronnikov Committed by Igor Munkin
Browse files

httpc: decode body in http response

@TarantoolBot document
Title: Document a body decoding in http response

New method "response:decode()" has been introduced for a HTTP response.
It allows to decode body to a Lua object. Decoding depends on content
type passed in HTTP header and decoding function for it defined in table
`http.decoders` or `http.new().decoders`. Function `response:decode()`
will raise an error when content type is present in the response, but
there is no appropriate decoder.

By default decoders for the following content types are defined:

- to JSON with content-type "application/json"
- to MsgPack with content-type "application/msgpack"
- to YAML with content-type "application/yaml"

If a content type is not present in the response, :decode() assumes
"application/json".

```
tarantool> resp = require('http.client').put(
    'http://127.0.0.1:8080', '{"productId": 123456, "quantity": 100}')
---
...

tarantool> resp.body
---
- '{"productId": 123456, "quantity": 100}'
...

tarantool>
tarantool> resp:decode()
---
- productId: 123456
- quantity: 100
...

tarantool>
```

For content types missed in `http.decoders` user could define it's own
by defining a new record with a key equal to desired MIME type in
lowercase and it's decoding function that must accept HTTP body, content
type and must return a decoded value:

```
local http = require("http")
local xml = require("luarapidxml")

http.decoders = {
    ['application/xml'] = function(body, _content_type)
        return xml.decode(body)
    end,
}
```

Closes #6833
parent 4818e988
No related branches found
No related tags found
Loading
Loading
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment