先用lua脚本编写好对应的接口功能"ikong_api.lua"
-- Require Modules
local conf = require "ik_config"
local cjson = require "cjson.safe"
local precheck = require "ik_precheck"
-- Performance Optimization
local pcall = pcall
local error = error
local str_format = string.format
local io_open = io.open
local math_randomseed = math.randomseed
local math_rand = math.random
local new_timer = ngx.timer.at
local DEBUG = ngx.DEBUG
local INFO = ngx.INFO
local ERR = ngx.ERR
local HTTP_OK = ngx.HTTP_OK
local cjson_encode = cjson.encode
local debug_mode = ngx.config.debug
local ngx_log = ngx.log
local ngx_var = ngx.var
local ngx_now = ngx.now
local ngx_redirect = ngx.redirect
local ngx_exit = ngx.exit
local ngx_header = ngx.header
local ngx_say = ngx.say
local ik_xx_key = conf.ik_xx_key
local _M = {}
_M._VERSION = '1.0.0'
-- enable check
local function enable()
-- response data
ngx_say(cjson_encode({
["success"] = true,
["msg"] = ""
})
end
-- disable check
local function disable()
ngx_exit(HTTP_OK)
end
local function update_conf()
ngx_exit(HTTP_OK)
end
-- check timeout
local function check_timeout()
ngx_exit(HTTP_OK)
end
-- get status
local function status()
ngx_exit(HTTP_OK)
end
if ngx_var.request_method == "POST" then
if ngx_var.uri == conf.ik_api_enable then
return enable()
end
if ngx_var.uri == conf.ik_api_disable then
return disable()
end
if ngx_var.uri == conf.ik_api_conf then
return update_conf()
end
if ngx_var.uri == conf.ik_api_check_timeout then
return check_timeout()
end
elseif ngx_var.request_method == "GET" then
if ngx_var.uri == conf.ik_api_status then
return status()
end
end
return ngx_exit(HTTP_FORBIDDEN)
编写一个lua的常量类,local conf = require "ik_config"
local _M = {}
_M._VERSION = '1.0.0'
-- api
_M.ik_api_enable = "/ikong-api/enable"
_M.ik_api_disable = "/ikong-api/disable"
_M.ik_api_conf = "/ikong-api/conf"
_M.ik_api_check_timeout = "/ikong-api/check-timeout"
_M.ik_api_status = "/ikong-api/status"
return _M
上面的代码中通过如下代码引入
local conf = require "ik_config"
这样我们就可以用一下方式对比请求中的uri与常量是否相等,如果相等,则可以执行对应lua的功能函数,并返回
if ngx_var.uri == conf.ik_api_enable then
return enable()
end
if ngx_var.uri == conf.ik_api_disable then
return disable()
end
if ngx_var.uri == conf.ik_api_conf then
return update_conf()
end
nginx下加入配置
# ikong server
server {
listen 8009;
location ~ ^/ikong-api/([-_a-zA-Z0-9]+) {
allow 127.0.0.1;
deny all;
content_by_lua_file /Users/ikong/ikong_api.lua;
}
}
具体请求处理流程如下
- 监听8009端口,接收请求;
- 只接收包含"ikong-api" 路径的请求
- 所有请求都经过 "content_by_lua_file" 指定的lua脚本"ikong_api.lua"
- "ikong_api.lua"脚本对比当前请求的ngx_var.uri 与 常量是否相等
- 执行具体的业务功能函数
细化后的流程如下图所示
请大佬们指正