Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http/request: Add :set_form_data method #26

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/modules/http.request.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions http/request.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/request_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down