04-OpenResty ngx lua API介绍

PS :

一、示例 :客户端提交base64数据,在lua解析后返回客户端

1.1、nginx conf

        location /decode_info {
            content_by_lua_file lua/decode_info.lua;
        }

1.2、decode_info.lua

# vim lua/decode_info.lua

local json = require "cjson"            -- require 表示引入一个库,引入cjosn

ngx.req.read_body()                     -- 调用 ngx lua api 获取http 请求 body
local args = ngx.req.get_post_args()    -- 再次获取 post 参数

if not args or not args.info then       -- 如果post请求的参数有为空的则通过 HTTP_BAD_REQUEST 抛出 400
    ngx.exit(ngx.HTTP_BAD_REQUEST)      -- ngx lua api
end

local client_ip = ngx.var.remote_addr   -- ngx lua api  ngx.var 表示获取nginx自己的值,remote_addr为nginx中的客户端地址
local user_agent = ngx.req.get_headers()['user-agent'] or ''    -- 读取 post请求的头部信息,如果未读到则为空
local info = ngx.decode_base64(args.info)   -- 使用ngx lua api base64 方法将post参数信息进行编码

local response = {}
response.info = info
response.ip = client_ip
response.user_agent = user_agent

ngx.say(json.encode(response))

1.3、访问测试

x# systemctl restart openresty
# curl -i --data 'info=5L2g5aW95ZWK77yMaGVsbG8gd29ybGQ=' http://127.0.0.1/decode_info
HTTP/1.1 200 OK
Server: openresty/1.19.3.1
Date: Tue, 18 May 2021 15:01:41 GMT
Content-Type: application/octet-stream
Transfer-Encoding: chunked
Connection: keep-alive

{"ip":"127.0.0.1","user_agent":"curl\/7.58.0","info":"你好啊,hello world"}
posted @ 2021-05-18 22:36  SRE运维充电站  阅读(235)  评论(0编辑  收藏  举报