From ad28aa3ae24f8c571570640d7d915d633405913a Mon Sep 17 00:00:00 2001 From: daurnimator Date: Wed, 4 May 2016 23:05:38 +1000 Subject: [PATCH 1/2] http/request: Add :set_form_data method --- doc/index.md | 7 +++++++ http/request.lua | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/doc/index.md b/doc/index.md index f21961b8..58cea988 100644 --- a/doc/index.md +++ b/doc/index.md @@ -690,6 +690,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:clone()` {#http.request:clone} Creates and returns a clone of the request. diff --git a/http/request.lua b/http/request.lua index 8cee796b..c4822482 100644 --- a/http/request.lua +++ b/http/request.lua @@ -273,6 +273,13 @@ function request_methods:set_body(body) end 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 + function request_methods:go(timeout) local deadline = timeout and (monotime()+timeout) From c8b2c21e1007e5307a14fa0620634c5f43c80914 Mon Sep 17 00:00:00 2001 From: daurnimator Date: Wed, 4 May 2016 23:28:23 +1000 Subject: [PATCH 2/2] spec/request_spec: Add test for :set_form_data --- spec/request_spec.lua | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/spec/request_spec.lua b/spec/request_spec.lua index 0c3b0ef7..9feb57db 100644 --- a/spec/request_spec.lua +++ b/spec/request_spec.lua @@ -144,6 +144,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) local headers = require "http.headers" it(":handle_redirect works", function() local orig_req = request.new_from_uri("http://example.com")