openresty 學習筆記二:獲取請求數據
openresty 獲取POST或者GET的請求參數。這個是要用openresty 做接口必須要做的事情。
這里分幾種類型:GET,POST(urlencoded),POST(form-data)。可以根據需要選擇某種提交請求的方式,也可以集合封裝成一個工具庫來使用
GET 請求
GET的請求數據比較簡單
function _M.get(self) local getArgs = {} getArgs = ngx.req.get_uri_args() return getArgs end
POST(urlencoded) 請求
urlencoded類型的POST請求數據也比較簡單
function _M.post_urlencoded(self) local postArgs = {} postArgs = ngx.req.get_post_args() return postArgs end
POST(form-data) 請求
form-data類型的POST請求數據就比較復雜,需要進行字符串分割(lua好像不帶split方法),所以首先要寫一個split方法
function _M.split(self,s, delim) if type(delim) ~= "string" or string.len(delim) <= 0 then return nil end local start = 1 local t = {} while true do local pos = string.find (s, delim, start, true) -- plain find if not pos then break end table.insert (t, string.sub (s, start, pos - 1)) start = pos + string.len (delim) end table.insert (t, string.sub (s, start)) return t end
獲取form-data的請求參數需要用到upload庫來獲取表單,這個庫安裝openresty默認已經帶了,也可以上GITHUB下載最新版本
local upload = require "resty.upload" local form, err = upload:new(4096) function _M.post_form_data(self,form,err) if not form then ngx.log(ngx.ERR, "failed to new upload: ", err) return {} end form:set_timeout(1000) -- 1 sec local paramTable = {["s"]=1} local tempkey = "" while true do local typ, res, err = form:read() if not typ then ngx.log(ngx.ERR, "failed to read: ", err) return {} end local key = "" local value = "" if typ == "header" then local key_res = _M:split(res[2],";") key_res = key_res[2] key_res = _M:split(key_res,"=") key = (string.gsub(key_res[2],"\"","")) paramTable[key] = "" tempkey = key end if typ == "body" then value = res if paramTable.s ~= nil then paramTable.s = nil end paramTable[tempkey] = value end if typ == "eof" then break end end return paramTable end args = _M:post_form_data(form, err)
根據請求類型不同使用不同方法進行獲取
根據需要,也可以將其合並起來