openresty +lua 知识点

openresty +lua 知识点,第1张

openresty +lua 知识点 openresty +lua 知识点 1、动态设置头信息

nginx.conf

 location /api {
			access_by_lua_file lua/setApiHeader.lua;
            proxy_pass http://gateway;
        }

setApiHeader.lua

local cjson=require "cjson"
local item_cache=ngx.shared.item_cache
local headers=ngx.req.get_headers()
ngx.log(ngx.INFO, "setApiHeader string:", cjson.encode(headers) )
-- Authorization: bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvYXV0aEV4cGlyZSI6MTA4MDAsImNyZWF0ZVRpbWUiOjE2NDA1Njc2NjExOTEsInVzZXJfbmFtZSI6ImFkbWluIiwibmlja05hbWUiOiLmt7HlnLPluILmsYnkupHnp5HmioDmnInpmZDlhazlj7giLCJzY29wZSI6WyJhbGwiXSwiY29tcGFueSI6IuaxieS6keenkeaKgCIsImV4cCI6MTY0MDU3ODQ2MSwidXNlcklkIjoxLCJqdGkiOiJkMzhiMTk4My00YmVkLTQxZTMtODUzMS0xMTFiMmVjZWEwNDkiLCJjbGllbnRfaWQiOiJtYWdpYyJ9.-Xks77yz1xfNoLzo9zr5tKNRXzrU0SBYEbbCEWnYcgQ
local str=headers.Authorization
if(str==nil) then 
	local request_args_tab = ngx.req.get_uri_args()
	ngx.log(ngx.INFO, "setApiHeader request_args_tab:", cjson.encode(request_args_tab))
	if(request_args_tab.token~=nil) then 
	str="bearer "..request_args_tab.token
	end
	ngx.log(ngx.INFO, "setApiHeader request_args_tab str:", str)
end
	
if(str~=nil) then 
	local key=string.sub(str,8,string.len(str))
	ngx.log(ngx.INFO, "setApiHeader key:", key )
	ngx.log(ngx.INFO, "setApiHeader val:", item_cache:get(key))
	local str2=item_cache:get(key)
	if(str2~=nil) then 
	local head=cjson.decode(item_cache:get(key))
	ngx.log(ngx.INFO, "setApiHeader headuserToken:", head.userToken )
	ngx.log(ngx.INFO, "setApiHeader headappToken:", head.appToken )
	ngx.req.set_header("appToken", head.appToken)
	ngx.req.set_header("userToken", head.userToken)
	ngx.log(ngx.INFO, "setApiHeader 解析后的headers:", cjson.encode(ngx.req.get_headers()))
	end
end
2、设置ws 代理

nginx.conf

http{
  # resolve websocket
    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }
  server{
     location /api {
            # resolve websocket
            proxy_set_header Upgrade $http_upgrade;
            # resolve websocket
            proxy_set_header Connection "upgra
			
            proxy_pass http://gateway/
        }
  }
}
3、http_util 封装的http

下载对应的http https://github.com/ledgetech/lua-resty-http/tree/master/lib/resty

nginx.conf

http{
	# lua 
    lua_package_path "/usr/local/openresty/lualib/?.lua;;";
    #c模块     
    lua_package_cpath "/usr/local/openresty/lualib/?.so;;";  
}

http_util.lua

-- http_util.lua
local http_util = {}

local http = require("resty.http")
local timeout = 60000

local function newClient()
    local httpC = http.new()
    httpC:set_timeout(timeout)
    return httpC
end

local contentType = "Content-Type"
local jsonEncode = "application/json; charset=utf-8"
local cJson = require("cjson")

-- httpGet
function http_util.httpGet(url)
    local httpc = newClient()
    local res, err = httpc:request_uri(url, {
        method = "GET",
        headers = {
            [contentType] = jsonEncode,
        }
    })
    if err or (not res) then
        ngx.log(ngx.ERR, "http get failed, err: ", err)
        return nil
    end
    ngx.log(ngx.INFO, "http get response body:  ", res.body)
    if res.status == ngx.HTTP_OK then
        return cJson.decode(res.body)
    end
end


function http_util.httpGet2(url,headers)
	local httpc = newClient()
	headers.contentType=jsonEncode
    local res, err = httpc:request_uri(url, {
        method = "GET",
        headers =headers
    })
	ngx.log(ngx.INFO, "http get, url= ", url, "  http get, headers= ", cJson.encode(headers))

    if err or (not res) then
        ngx.log(ngx.ERR, "http get failed, err: ", err)
        return nil
    end
    ngx.log(ngx.INFO, "http get response body: ", res.body)
    if res.status == ngx.HTTP_OK then
        return cJson.decode(res.body)
    end
end





-- httpPost body需要进行编码,如k=v k,v分别进行urlEncode
function http_util.httpPost(url, body)
    local httpc = newClient()
    local res, err = httpc:request_uri(url, {
        method = "POST",
        body = body,
        headers = {
            [contentType] = jsonEncode,
        }
    })
    ngx.log(ngx.INFO, "http post, url= ", url, "  http post, body= ", body)

    if err or (not res) then
        ngx.log(ngx.ERR, "http post failed, err: ", err)
        return nil
    end
    ngx.log(ngx.INFO, "http post response body: ", res.body)
    if res.status == ngx.HTTP_OK then
        return cJson.decode(res.body)
    end
end


-- httpPost body需要进行编码,如k=v k,v分别进行urlEncode
function http_util.httpPost2(url, body,headers )
    local httpc = newClient()
    headers.contentType=jsonEncode
    local res, err = httpc:request_uri(url, {
        method = "POST",
        body = body,
        headers = headers 
    })
    ngx.log(ngx.INFO, "http post, url= ", url, "  http post, headers= ", cJson.encode(headers), "  http post, body= ", body)
    if err or (not res) then
        ngx.log(ngx.ERR, "http post failed, err: ", err)
        return nil
    end
    ngx.log(ngx.INFO, "http post response body: ", res.body)
    if res.status == ngx.HTTP_OK then
        return cJson.decode(res.body)
    end
end

function http_util.getcookie(cookie,name) 
    local cookievalue = nil;
    if (cookie ~= '') then
        local cookies = http_util.Split(cookie,';');
		for k,v in pairs(cookies) do
			local splits = http_util.Split(v,'=');
            -- 判断这个cookie的参数名是不是我们想要的
            if (splits[1]==name) then
                cookievalue = splits[2];
                break;
            end
		end

    end
    return cookievalue;
end

function http_util.Split(szFullString, szSeparator)
local nFindStartIndex = 1
local nSplitIndex = 1
local nSplitArray = {}
while true do
   local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
   if not nFindLastIndex then
    nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
    break
   end
   nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
   nFindStartIndex = nFindLastIndex + string.len(szSeparator)
   nSplitIndex = nSplitIndex + 1
end
return nSplitArray
end

return http_util

4、缓存

nginx.conf

http{
    lua_shared_dict item_cache 2500m; 
}

lua脚本

-- 获取本地缓存对象
local item_cache = ngx.shared.item_cache

-- 存储, 指定key、value、过期时间,单位s,默认为0代表永不过期   data 不能是对象 对象需要转换cjson.encode(data)
item_cache:set(key, data, 0)
  
item_cache:get(key)

item_cache:delete(key)

5、获取请求参数
-- 获取GET请求参数
-- local request_args_tab = ngx.req.get_uri_args()
-- for k, v in pairs(request_args_tab) do
--   ngx.log(ngx.INFO, "k:", k,"v",v )
-- end
--获取post body参数
--local data= cjson.decode(ngx.req.get_body_data())
--ngx.log(ngx.INFO, " string:",  data.appId)
--ngx.log(ngx.INFO, " string:",  cjson.encode(data))

## 6、获取cookie

local http_util= require('http_util')
local getcookie= http_util.getcookie

local cookie = ngx.var.http_cookie
local userToken=getcookie(cookie,"TRUSTED_SESSIONID")
7、获取请求
local headers = ngx.req.get_headers()
ngx.log(ngx.INFO, " string:", cjson.encode(headers) )
8、解决使用一个header 发送两次post,第二次post报错

同一个请求,一样的header 发送两次后,第一次post后,第二次不管get还是post都不能请求,暂时只能设置headers.connection=“close”

headers.connection="close"
local itemJSON = httpPost2(Url,cjson.encode(data), headers)
local itemJSON2 = httpPost2(Url,cjson.encode(data), headers)
9、转发页面
ngx.redirect(redUrl)
10、websocket鉴权

将token加到url后面

url?token=xxxx

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5682675.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存