需求:根據客戶需求,可以在ngx下 通過lua做接口二次封裝再次轉發給用戶或第三方
場景:對返回值有要求的、接口屏蔽字段、或做一些業務上的驗證等
1、windows直接下載openresty 解壓即可,就完成了windows下使用lua的開發環境
2、配置:
a、在nginx.conf里http下配置如下代碼:
include mime.types; default_type application/octet-stream; lua_package_path "/lualib/?.lua;;"; #lua 模塊 lua_package_cpath "/lualib/?.so;;"; #c模塊 include lua.conf; #導入自定義lua配置文件 resolver 8.8.8.8;
b、在nginx.conf同目錄創建lua.conf文件專門存放lua的路由配置
#lua.conf server { charset utf-8; #設置編碼 listen 80; server_name _; location /user { default_type 'text/html'; content_by_lua_file lua/api/userController.lua; #相對於nginx安裝目錄 } }
c、在ngx根目錄下的lua文件夾里創建“api”文件夾,並且在里面添加userController.lua 處理文件類,例如代碼如下:
local request_method = ngx.var.request_method local args = nil --1、獲取參數的值 獲取前端提交參數 if "GET" == request_method then args = ngx.req.get_uri_args() elseif "POST" == request_method then ngx.req.read_body() args = ngx.req.get_post_args() end --2、組合url請求Get/Post請求 並獲取參數 local http = require "resty.http" local httpc = http.new() local url = "http://xxxxx/user/login/"..args["userid"].."/"..args["pass"] local resStr --響應結果 local res, err = httpc:request_uri(url, { method = "GET", --args = str, body = "a=1&b=2", headers = { ["Content-Type"] = "application/json", } }) --3、開始重新組合參數 例子 可根據返回的JSON自己處理 local cjson = require "cjson" local sampleJson = [[{"age":"23","testArray":{"array":[8,9,11,14,25]},"Himi":"himigame.com"}]]; --解析json字符串 local data = cjson.decode(sampleJson); --打印json字符串中的age字段 ngx.say(data["age"]); --打印數組中的第一個值(lua默認是從0開始計數) ngx.say(data["testArray"]["array"][1]); --4、打印輸出新返回值 ngx.say(res.body)
3、啟動ngx服務器,訪問地址,路由為user