OpenResty徹底開發指南:構建百萬級別併發的Web應用 綜合實例

 --功能描述html

-- 實現基本的時間服務,具體功能是
--1:只支持GET和POST方法
--2:只支持HTTP 1.1/2協議
--3:只容許某些用戶訪問
--4:GET方法獲取當前時間,以HTTP時間格式輸出
--5:POST方法在請求體力傳入時間戳,服務器轉換爲http時間格式
--6:可使用URI參數 「need_encode=1」輸出會作base64編碼

 --設計服務器

-- 依據openresty的階段式處理邏輯,能夠把整個應用劃分爲四個部分,每一個部分都有一個獨立的lua文件
--1:rewrite_by_lua:正確性檢查
--2:accessby_lua:使用白名單作訪問控制
--3:content_by_lua:產生響應內容
--4:body_filter_by_lua:加工數據,base64編碼

 --正確性檢查curl

rewrite_demo1.lua文件
--1:rewrite_by_lua:正確性檢查
local method=ngx.req.get_method() -- 獲取請求方法
if method ~= "GET" and method ~= "POST" then
    ngx.header['Allow'] = 'GET,POST' --方法錯誤返回Allow頭字段
    ngx.exit(405)                    -- 返回狀態碼405 結束請求
end

local ver = ngx.req.http_version() --獲取協議版本號
if ver  < 1.1 then
    ngx.log(ngx.WARN,"VERSION IS LOWER THEN 1.1" .. ver)
    ngx.exit(400)
end
ngx.ctx.encode = ngx.var.arg_need_encode -- 取URI參數裏need_ecncode字段
ngx.header.content_length = nil          -- 刪除長度頭,謎面客戶端接受錯誤

 --白名單控制函數

access_demo1.lua
local white_list={... } -- 若干白名單ip地址
local ip = ngx.var.remote_addr --獲取客戶端地址

if not white_list[ip] then
    ngx.log(ngx.WARN, ip,"access was refaused")
    ngx.exit(403)
end

 -- 業務邏輯post

content_demo1.lua
local action_get=function()
    ngx.req.discard_body() -- 顯示丟棄請求體

    local tmpstamp = ngx.time() -- 獲取當前時間戳
    ngx.say(ngx.http_time(tmpstamp)) --轉換爲http格式
end

local action_post = function()
    ngx.req.read_body() -- 要求非阻塞讀取請求體
    local data = ngx.req.get_body_data() -- 獲取請求體數據
    local num = tonumber(data) -- 轉換數字

    if not num then
        ngx.log(ngx.ERR, num, "is ")
        ngx.exit(400)
    end
    ngx.say(ngx.http_time(num))
end

local actions={ --一個表映射方法與處理函數
    GET = action_get,
    post= action_post
}

local fun = ngx.req.get_method() -- 獲取請求方法
actions[fun]()

 --數據加工測試

if ngx.status ~= ngx.HTTP_OK then--錯誤信息不會編碼
    return
end

if ngx.ctx.encode then
    ngx.arg[1] = ngx.encode_base64(ngx.arg[1]) -- 改寫響應體數據, 對數據作base64編碼
end

 -- 部署應用編碼

location = /demo1 {
    rewrite_by_lua_file             /usr/openResty/src/rewrite_demo1.lua;
    access_by_lua_file             /usr/openResty/src/access_demo1.lua;
    content_by_lua_file             /usr/openResty/src/content_demo1.lua;
    body_filter_by_lua_file             /usr/openResty/src/body_filter_demo1.lua;
}

 --測試lua

--測試
--curl ' 127.0.0.1/example '                            #發送GET 請求
--curl ' 127.0.0.1/example ' d ' 1516765407 '             #發送POST 請求
--curl ' 127.0.0.1/example '-X DELETE                     #發送DE LETE 請求,返回405
--curl ' 127.0.0.1/example?need_encode=l '                  #要求Base64 編碼
相關文章
相關標籤/搜索