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

可以看到序列化的对象

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章