lua脚本写http请求
时间: 2024-01-05 15:19:10 浏览: 41
根据提供的引用内容,无法确定您所说的“lua脚本写http请求”是指在lua脚本中发起http请求,还是在接收到http请求后在lua脚本中处理请求。因此,我将为您提供这两种情况的回答。
1. 在lua脚本中发起http请求
可以使用Lua的socket库来发起http请求。以下是一个简单的示例:
```lua
local http = require("socket.http")
local response, status = http.request("http://www.example.com")
if status == 200 then
print(response)
end
```
在这个示例中,我们使用socket.http库中的request函数来发起http请求。如果请求成功,我们将打印响应内容。
2. 在接收到http请求后在lua脚本中处理请求
根据提供的引用内容,我们可以看到在nginx配置中使用了content_by_lua_file指令来指定一个lua脚本来处理http请求。因此,我们可以在这个lua脚本中处理http请求。以下是一个简单的示例:
```lua
-- 导入http库
local http = require("resty.http")
-- 创建http客户端
local httpc = http.new()
-- 发起http请求
local res, err = httpc:request_uri("http://www.example.com", {
method = "GET"
})
-- 检查请求是否成功
if not res then
ngx.say("failed to request: ", err)
return
end
-- 打印响应内容
ngx.say(res.body)
```
在这个示例中,我们使用了OpenResty提供的resty.http库来发起http请求。我们首先创建了一个http客户端,然后使用request_uri函数来发起http请求。如果请求成功,我们将打印响应内容。