03-OpenResty入门

PS :奇虎360 公司开源的 OpenResty最佳实践的书籍地址 https://github.com/moonbingbing/openresty-best-practices

一、ngx lua api 获得随机字符串

1.1、nginx conf

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

1.2、get_random_string.lua

image

# vim lua/get_random_string.lua

local args = ngx.req.get_uri_args()  -- 获取uri中的参数赋值给args变量
local salt = args.salt

if not salt then                     -- 如果uri参数中没有salt则通过 HTTP_BAD_REQUEST 抛出 400
    ngx.exit(ngx.HTTP_BAD_REQUEST)
end

local string = ngx.md5(ngx.time() .. salt)  -- ngx.time()表示获取系统事件, .. 表示字符串相加,然后调用 ngx lua 中的 ngx.md5 api计算了一个MD5值
ngx.say(string)

1.3、访问测试

# systemctl restart openresty

# 未携带参数
# curl 127.0.0.1/get_random_string
<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty/1.19.3.1</center>
</body>
</html>

# 携带参数
# curl 127.0.0.1/get_random_string?salt=123
80a3bf37aae208de6a35c12862f27077
posted @ 2021-05-18 22:31  SRE运维充电站  阅读(119)  评论(0编辑  收藏  举报