httpc: encode body in http request
client_object:request() could pass a body as a string value to HTTP request when body is used. User must encode body to a string value as a preparation step. However, we can do encoding for user automatically when it possible. @TarantoolBot document Title: Document body encoding in http request Now user could pass a "body" option as a value with standard Lua types (table, nil, string, userdata, cdata, boolean or number) as well as Tarantool's own data types like decimal, uuid, datetime. In such case that value will be encoded to a string automatically where it possible. Encoding depends on body's data type: `nil` converted to an empty string, types (`string`, `number`, `boolean` and `nil`) will be converted to a string using standard Lua function `tostring()`, types cdata, userdata and tables will be encoded by functions defined in `http.encoders` or `http.new().encoders` table. In latter case encoding function depends on a content type passed to HTTP request using HTTP header. Default content type "application/json" and appropriate encoder are used when content type is missed in HTTP request. By default encoders for the following content types are defined: - "application/json" - "application/msgpack" - "application/yaml" For content types missed in `http.encoders` user could define it's own encoder by defining a new record with a key equal to desired MIME type in lowercase and it's encoding function that must accept HTTP body and content type and must return a string with serialized data: ``` local http = require("http") local xml = require("luarapidxml") http.encoders = { ['application/xml'] = function(body, _content_type) return xml.encode(body) end, } ``` Be careful with defining your own encoding function - header with content type could contain content type like "text/html" as well as a header options [1], like "text/html; charset=UTF-8". Content type is passed to encoder function *with* options. JSON encoder will use default configuration settings defined in JSON module (see `json.cfg()`). Header with content type will be set to "application/json" if it was not defined by user in request's options. ``` local http = require("http") local client = http.new() local body = { a = 1, b = 2, c = 3, } client:request("POST", uri, body) client:post(uri, body) ``` 1. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type Part of #6833
Showing
- changelogs/unreleased/gh-6833-encode-body-http-request.md 6 additions, 0 deletionschangelogs/unreleased/gh-6833-encode-body-http-request.md
- src/lua/httpc.lua 122 additions, 2 deletionssrc/lua/httpc.lua
- test/app-luatest/http_client_test.lua 206 additions, 0 deletionstest/app-luatest/http_client_test.lua
- test/app-luatest/http_client_unit_test.lua 178 additions, 0 deletionstest/app-luatest/http_client_unit_test.lua
- test/app-luatest/httpd.py 2 additions, 0 deletionstest/app-luatest/httpd.py
Loading
Please register or sign in to comment