openresty开发库
http客户端
配置openresty
连接http
local http = require("resty.http")
local http_instance = http.new()
local response, error = httpc:request_uri("http://s.taobao.com", {
method = "GET",
path = "/search?q=hello",
headers = {
["User-Agent"] =
"Mozilla/5.0 (Windows NT 6.1; WOW64) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36"
}
})
if not response then
ngx.say(error)
return
end
ngx.status = response.status
for k, v in pairs(response.headers) do
if k ~= "Transfer-Encoding" and k ~= "Connection" then
ngx.header[k] = v
end
end
ngx.say(response.body)
http_instance:close()
cjson解析
local cjson = require("cjson")
local obj = {
id = 1,
name = "zhangsan",
age = nil,
is_male = false,
hobby = {"film", "music", "read"}
}
local str = cjson.encode(obj)
ngx.say(str)
str = '{"hobby":["film","music","read"],
"is_male":false,
"name":"zhangsan",
"id":1,
"age":null}'
local obj = cjson.decode(str)
ngx.say(obj.id, obj.name, obj.age, obj.hobby[1])
djson解析
local dkjson = require("dkjson")
local obj = {
id = 1,
name = "zhangsan",
age = nil,
is_male = false,
hobby = {"film", "music", "read"}
}
local str = dkjson.encode(obj, {indent = true})
str = '{"hobby":["film","music","read"],
"is_male":false,
"name":"zhangsan",
"id":1,
"age":null}'
local obj, pos, err = dkjson.decode(str, 1, nil)
ngx.say(obj.id, obj.name, obj.age, obj.hobby[1])