openresty 的http和cjson模块

 

1.http模块

Openresty没有提供默认的Http客户端,需要下载第三方的http客户端。

https://github.com/ledgetech/lua-resty-http/releases
压缩包里面包括两个lua文件:
http.lua
http_headers.lua

把它们拷贝到  /usr/local/openresty/example/lualib/resty

 

vim example.conf

location /lua_http {
	default_type 'text/html';
	lua_code_cache on;
	content_by_lua_file /usr/local/openresty/example/lua/test_http.lua;
}

vim test_http.lua

local http = require("resty.http")  
local httpc = http.new()    
local resp, err = 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 resp then  
    ngx.say("request error :", err)  
    return  
end   
 
ngx.status = resp.status    
  
for k, v in pairs(resp.headers) do  
    if k ~= "Transfer-Encoding" and k ~= "Connection" then  
        ngx.header[k] = v  
    end  
end  
  
ngx.say(resp.body)    
httpc:close()  


vim nginx.conf

# http 块添加DNS解析
resolver 8.8.8.8; 

访问 192.168.1.7:8083 跳转到淘宝网

 

2. cjson模块

在openresty默认内嵌了lua_cjson模块,用来序列化数据。

vim example.conf

 location  /lua_cjson {  
   default_type 'text/html';  
   lua_code_cache on;  
   content_by_lua_file /usr/local/openresty/example/lua/test_cjson.lua;  
 } 

vim test_cjson.lua

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, "<br/>")  
  
 
str = '{"hobby":["film","music","read"],"is_male":false,"name":"zhangsan","id":1,"age":null}'  
local obj = cjson.decode(str)  
  
ngx.say(obj.age, "<br/>")  
ngx.say(obj.age == nil, "<br/>")  
ngx.say(obj.age == cjson.null, "<br/>")  
ngx.say(obj.hobby[1], "<br/>")  

访问:http://192.168.1.7:8083/lua_cjson

可以看到序列化的对象

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值