diff --git a/doc/modules/http.request.md b/doc/modules/http.request.md index b4f11713..3295d136 100644 --- a/doc/modules/http.request.md +++ b/doc/modules/http.request.md @@ -119,6 +119,13 @@ Allows setting a request body. `body` may be a string, function or lua file obje - If `body` is a lua file object, it will be [`:seek`'d](http://www.lua.org/manual/5.3/manual.html#pdf-file:seek) to the start, then sent as a body. Any errors encountered during file operations **will be thrown**. +### `request:set_form_data(dict)` {#http.request:set_form_data} + +Turns the request into a POST request with a `"application/x-www-form-urlencoded"` encoded body. + +`dict` should be a table with string keys and string values. + + ### `request:go(timeout)` {#http.request:timeout} Performs the request. diff --git a/http/request.lua b/http/request.lua index b4b4fd06..0d50214f 100644 --- a/http/request.lua +++ b/http/request.lua @@ -331,6 +331,13 @@ function request_methods:set_body(body) return true end +function request_methods:set_form_data(form) + local body = http_util.dict_to_query(form) + self.headers:upsert(":method", "POST") + self.headers:upsert("content-type", "application/x-www-form-urlencoded") + return self:set_body(body) +end + local function non_final_status(status) return status:sub(1, 1) == "1" and status ~= "101" end diff --git a/spec/request_spec.lua b/spec/request_spec.lua index d718916d..e3575d69 100644 --- a/spec/request_spec.lua +++ b/spec/request_spec.lua @@ -170,6 +170,17 @@ describe("http.request module", function() req:set_body(io.tmpfile()) assert.same("100-continue", req.headers:get("expect")) end) + it(":set_form_data works", function() + local req = request.new_from_uri("http://example.com") + assert.same("GET", req.headers:get(":method")) + assert.falsy(req.headers:has("content-type")) + req:set_form_data { + foo = "bar"; + } + assert.same("POST", req.headers:get(":method")) + assert.same("application/x-www-form-urlencoded", req.headers:get("content-type")) + assert.same("foo=bar", req.body) + end) describe(":handle_redirect method", function() local headers = require "http.headers" it("works", function()