lua脚本使用,单个及多个参数post请求

1、脚本内容 access_token_check.lua:

token = ngx.req.get_headers()['token']

if (token == nil or token == '') then
    ngx.header['Content-Type'] = 'application/json; charset=utf-8'
    ngx.print('{"errorCode":"401","value":"无访问权限!","data":null}')
    ngx.exit(ngx.OK)
end


res = ngx.location.capture(
        '/gateway/api/gateway/checkToken',
        {
            method = ngx.HTTP_POST,
            --单个固定参数
            body = '{"channelId":"1"}'
        }
)
if (res ~= nil
        and res.status ~= nil
        and res.status == ngx.HTTP_OK) then

    --放入头部
    ngx.req.set_header('userId', res.header['userId'])
    ngx.req.set_header('channelId', res.header['channelId'])
    ngx.req.set_header('platform', res.header['platform'])


    --获取请求的URI
    local request_uri = ngx.var.request_uri
    --日志打印
    ngx.log(ngx.ERR, request_uri)
    ngx.log(ngx.ERR,"-----------------------------------------")
    ngx.header['Content-Type'] = 'application/json; charset=utf-8'
    ngx.log(ngx.ERR, res.body)
    ngx.log(ngx.ERR, res.status)

    check_res = ngx.location.capture(
        '/gateway-login/api/checkRolePermission',
        {
            method = ngx.HTTP_POST,
            --多个动态参数
            body = '{"userId":"' .. res.header['userId'] .. '","requestUri":"' .. ngx.var.request_uri .. '"}'
        }
    )

    if (res ~= nil
        and res.status ~= nil
        and res.status ~= ngx.HTTP_OK) then
        ngx.print('{"errorCode":"401","value":"权限不足!","data":null}')
        ngx.exit(ngx.OK)
    end


else
    ngx.header['Content-Type'] = 'application/json; charset=utf-8'
    ngx.print('{"errorCode":"401","value":"无访问权限!","data":null}')
    ngx.exit(ngx.OK)


end

2、使用 

location /gateway{
       access_by_lua_file /usr/local/openresty/lualib/access_token_check.lua;
       proxy_pass http://gateway/;
    }

你可能感兴趣的:(服务器,lua,开发语言)