Skip to content

Commit

Permalink
fetch post body and files was seccessed.
Browse files Browse the repository at this point in the history
  • Loading branch information
alacner committed May 8, 2011
1 parent a326521 commit e194c26
Show file tree
Hide file tree
Showing 11 changed files with 581 additions and 44 deletions.
62 changes: 62 additions & 0 deletions example/nginx/boundary.lua
@@ -0,0 +1,62 @@
-- Copyright (C) Alacner Zhang (alacner@gmail.com)

module('nginx.boundary', package.seeall)

require ("nginx.kit")

function get(ct)
if not ct then return false end
local _,_,boundary = string.find (ct, "boundary%=(.-)$")
if not boundary then return false end
return "--"..boundary
end

--
-- Create a table containing the headers of a multipart/form-data field
--
function split(...)
local request_data, boundary = ...

if not request_data then return false end;
if not boundary then return false end;

local files, posts = {}, {}

local post_temp = nginx.kit.split(request_data, boundary)
for i,pd in ipairs(post_temp) do

local headers = {}
local hdrdata, post_val = string.match(pd, "(.+)\r\n\r\n(.+)\r\n")
--printl(hdrdata)

if hdrdata then
string.gsub (hdrdata, '([^%c%s:]+):%s+([^\n]+)', function(type,val)
type = string.lower(type)
headers[type] = val
end)
end

local t = {}
local hcd = headers["content-disposition"]
if hcd then
string.gsub(hcd, ';%s*([^%s=]+)="(.-)"', function(attr, val)
t[attr] = val
end)
-- Filter POST or FILE
if headers["content-type"] then
-- name,type,size,tmp_name,error
local file = {}
file['type'] = headers["content-type"]
file['name'] = t["filename"]
file['data'] = post_val;
file['size'] = string.len(post_val);

files[t.name] = file
else
posts[t.name] = post_val
end
end
end

return posts, files
end
26 changes: 26 additions & 0 deletions example/nginx/init.lua
@@ -0,0 +1,26 @@
-- Copyright (C) Alacner Zhang (alacner@gmail.com)

--module('nginx', package.seeall)

print = ngx.print

require("nginx.kit")
require("nginx.boundary")
require("nginx.urlcode")

print_r = nginx.kit.print_r

local ngx_post_request_data = ngx.post["request_data"]

ngx.post = nil

if ngx_post_request_data then
local posts, files = {}, {};
local boundary = nginx.boundary.get(ngx.header["Content-Type"])
if boundary then
posts, files = nginx.boundary.split(ngx_post_request_data, boundary)
else
nginx.urlcode.parsequery(ngx_post_request_data, posts)
end
ngx.post, ngx.files, posts, files = posts, files, nil, nil
end
25 changes: 23 additions & 2 deletions example/kit.lua → example/nginx/kit.lua
@@ -1,5 +1,6 @@
--Copyright (c) 2011-2015 Zhihua Zhang (alacner@gmail.com) -- Copyright (C) Alacner Zhang (alacner@gmail.com)
module('kit', package.seeall)
module('nginx.kit', package.seeall)


function print_r(sth) function print_r(sth)
if type(sth) ~= "table" then if type(sth) ~= "table" then
Expand Down Expand Up @@ -42,3 +43,23 @@ function print_r(sth)
_dump(sth) _dump(sth)
print(string.format(")\r\n")) print(string.format(")\r\n"))
end end


function split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
132 changes: 132 additions & 0 deletions example/nginx/lp.lua
@@ -0,0 +1,132 @@
----------------------------------------------------------------------------
-- Lua Pages Template Preprocessor.
--
-- @release $Id: lp.lua,v 1.15 2008/12/11 17:40:24 mascarenhas Exp $
----------------------------------------------------------------------------

local assert, error, getfenv, loadstring, setfenv = assert, error, getfenv, loadstring, setfenv

----------------------------------------------------------------------------
-- function to do output
local outfunc = "ngx.print"
--local outfunc = "print"
--local outfunc = "io.write"
-- accepts the old expression field: `$| <Lua expression> |$'
local compatmode = true

--
-- Builds a piece of Lua code which outputs the (part of the) given string.
-- @param s String.
-- @param i Number with the initial position in the string.
-- @param f Number with the final position in the string (default == -1).
-- @return String with the correspondent Lua code which outputs the part of the string.
--
local function out (s, i, f)
s = string.sub(s, i, f or -1)
if s == "" then return s end
-- we could use `%q' here, but this way we have better control
s = string.gsub(s, "([\\\n\'])", "\\%1")
-- substitute '\r' by '\'+'r' and let `loadstring' reconstruct it
s = string.gsub(s, "\r", "\\r")
return string.format(" %s('%s'); ", outfunc, s)
end


----------------------------------------------------------------------------
-- Translate the template to Lua code.
-- @param s String to translate.
-- @return String with translated code.
----------------------------------------------------------------------------
function translate (s)
s = string.gsub(s, "^#![^\n]+\n", "")
if compatmode then
s = string.gsub(s, "$|(.-)|%$", "<?lua = %1 ?>")
s = string.gsub(s, "<!%-%-$$(.-)$$%-%->", "<?lua %1 ?>")
end
s = string.gsub(s, "<%?(.-)%?>", "<?lua %1 ?>")
s = string.gsub(s, "<%%(.-)%%>", "<?lua %1 ?>")
s = string.gsub(s, "<%?lua lua(.-)%?>", "<?lua %1 ?>")
local res = {}
local start = 1 -- start of untranslated part in `s'
while true do
local ip, fp, target, exp, code = string.find(s, "<%?(%w*)[ \t]*(=?)(.-)%?>", start)
if not ip then break end
table.insert(res, out(s, start, ip-1))
if target ~= "" and target ~= "lua" then
-- not for Lua; pass whole instruction to the output
table.insert(res, out(s, ip, fp))
else
if exp == "=" then -- expression?
table.insert(res, string.format(" %s(%s);", outfunc, code))
else -- command
table.insert(res, string.format(" %s ", code))
end
end
start = fp + 1
end
table.insert(res, out(s, start))
return table.concat(res)
end


----------------------------------------------------------------------------
-- Defines the name of the output function.
-- @param f String with the name of the function which produces output.

function setoutfunc (f)
outfunc = f
end

----------------------------------------------------------------------------
-- Turns on or off the compatibility with old CGILua 3.X behavior.
-- @param c Boolean indicating if the compatibility mode should be used.

function setcompatmode (c)
compatmode = c
end

----------------------------------------------------------------------------
-- Internal compilation cache.

local cache = {}

----------------------------------------------------------------------------
-- Translates a template into a Lua function.
-- Does NOT execute the resulting function.
-- Uses a cache of templates.
-- @param string String with the template to be translated.
-- @param chunkname String with the name of the chunk, for debugging purposes.
-- @return Function with the resulting translation.

function compile (string, chunkname)
local f, err = cache[string]
if f then return f end
f, err = loadstring (translate (string), chunkname)
if not f then error (err, 3) end
cache[string] = f
return f
end

----------------------------------------------------------------------------
-- Translates and executes a template in a given file.
-- The translation creates a Lua function which will be executed in an
-- optionally given environment.
-- @param filename String with the name of the file containing the template.
-- @param env Table with the environment to run the resulting function.
local BOM = string.char(239) .. string.char(187) .. string.char(191)

function include (filename, env)
-- read the whole contents of the file
local fh = assert (io.open (filename))
local src = fh:read("*a")
fh:close()
if src:sub(1,3) == BOM then src = src:sub(4) end
-- translates the file into a function
local prog = compile (src, '@'..filename)
local _env
if env then
_env = getfenv (prog)
setfenv (prog, env)
end
prog ()
end
95 changes: 95 additions & 0 deletions example/nginx/urlcode.lua
@@ -0,0 +1,95 @@
----------------------------------------------------------------------------
-- Utility functions for encoding/decoding of URLs.
--
-- @release $Id: urlcode.lua,v 1.10 2008/01/21 16:11:32 carregal Exp $
----------------------------------------------------------------------------

module('nginx.urlcode', package.seeall)

----------------------------------------------------------------------------
-- Decode an URL-encoded string (see RFC 2396)
----------------------------------------------------------------------------
function unescape (str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end

----------------------------------------------------------------------------
-- URL-encode a string (see RFC 2396)
----------------------------------------------------------------------------
function escape (str)
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^0-9a-zA-Z ])", -- locale independent
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
return str
end

----------------------------------------------------------------------------
-- Insert a (name=value) pair into table [[args]]
-- @param args Table to receive the result.
-- @param name Key for the table.
-- @param value Value for the key.
-- Multi-valued names will be represented as tables with numerical indexes
-- (in the order they came).
----------------------------------------------------------------------------
function insertfield (args, name, value)
if not args[name] then
args[name] = value
else
local t = type (args[name])
if t == "string" then
args[name] = {
args[name],
value,
}
elseif t == "table" then
table.insert (args[name], value)
else
error ("CGILua fatal error (invalid args table)!")
end
end
end

----------------------------------------------------------------------------
-- Parse url-encoded request data
-- (the query part of the script URL or url-encoded post data)
--
-- Each decoded (name=value) pair is inserted into table [[args]]
-- @param query String to be parsed.
-- @param args Table where to store the pairs.
----------------------------------------------------------------------------
function parsequery (query, args)
if type(query) == "string" then
local insertfield, unescape = insertfield, unescape
string.gsub (query, "([^&=]+)=([^&=]*)&?",
function (key, val)
insertfield (args, unescape(key), unescape(val))
end)
end
end

----------------------------------------------------------------------------
-- URL-encode the elements of a table creating a string to be used in a
-- URL for passing data/parameters to another script
-- @param args Table where to extract the pairs (name=value).
-- @return String with the resulting encoding.
----------------------------------------------------------------------------
function encodetable (args)
if args == nil or next(args) == nil then -- no args or empty args?
return ""
end
local strp = ""
for key, vals in pairs(args) do
if type(vals) ~= "table" then
vals = {vals}
end
for i,val in ipairs(vals) do
strp = strp.."&"..escape(key).."="..escape(val)
end
end
-- remove first &
return string.sub(strp,2)
end
21 changes: 14 additions & 7 deletions example/t1.lua
@@ -1,10 +1,17 @@
--Copyright (c) 2011-2015 Zhihua Zhang (alacner@gmail.com) -- Copyright (C) Alacner Zhang (alacner@gmail.com)
--ngx.set_header('Location', "http://www.google.com");
--ngx.set_cookie('love', '123456') -- name, value, expire, path, domain, secure require("nginx")
--ngx.set_cookie('aa', 'ssssss') -- name, value, expire, path, domain, secure
print = ngx.print print_r(ngx)
local kit = require("kit") ngx.eof()
local print_r = kit.print_r do return end

require "lp"

do return end





--ngx.set_header('Content-Type', "image/png"); --ngx.set_header('Content-Type', "image/png");
ngx.set_header('Content-Type', "text/html"); ngx.set_header('Content-Type', "text/html");
Expand Down
7 changes: 7 additions & 0 deletions example/t2.lua
@@ -0,0 +1,7 @@
--Copyright (c) 2011-2015 Zhihua Zhang (alacner@gmail.com)
ngx.set_header('Content-Type', "text/html");
local print = ngx.print
print(os.time())
require "lp"
include('test.lp')
ngx.eof()

0 comments on commit e194c26

Please sign in to comment.