Skip to content

Instantly share code, notes, and snippets.

@suzumura-ss
Last active January 8, 2016 14:36
Show Gist options
  • Save suzumura-ss/52414e470cad7a8c0d7b to your computer and use it in GitHub Desktop.
Save suzumura-ss/52414e470cad7a8c0d7b to your computer and use it in GitHub Desktop.
upload request-body to other service
-- https://github.com/diegonehab/luasocket
local HTTP = require("socket.http")
local LTN12 = require("ltn12")
-- source for ngx.req.socket()
function source_tcpsock(handle, bytes)
bytes = tonumber(bytes)
if handle then
return function()
if bytes <= 0 then
return nil
end
local rsize = 2048
if bytes < rsize then
rsize = bytes
end
local chunk, err, partial = handle:receive(rsize)
if err then
ngx.log(ngx.ERR, "receive failed")
ngx.exit(500)
end
if not chunk then
chunk = partial
end
if chunk then
bytes = bytes - #chunk
end
return chunk
end
else
return LTN12.source.error('handle is nil')
end
end
-- upload uri
local post_uri = 'http://localhost:9292/teapot'
local headers = ngx.req.get_headers()
local reqtype = headers['content-type'] or 'application/json'
local reqsize = headers['content-length'] or '0'
local resbody = {}
local result, rescode, resheaders, resstatus = HTTP.request {
method = 'POST',
url = post_uri,
source = source_tcpsock(ngx.req.socket(), reqsize),
headers = {
["Content-Type"] = reqtype,
["Content-Length"] = reqsize
},
sink = LTN12.sink.table(resbody)
}
ngx.status = rescode
ngx.header.content_type = resheaders['content-type']
ngx.say(table.concat(resbody))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment