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

可以看到序列化的對象

 

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