nginx + lua 根据post请求参数做转发

本文介绍如何使用Lua脚本和Nginx配置文件实现API请求的智能路由,根据HTTP请求方法(GET或POST)及请求参数,动态选择执行不同的API逻辑。具体通过解析JSON参数,判断用户请求类型,进而调用相应的API处理模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        location / {
             content_by_lua_file "lua/dispatch.lua";
         }


        location @user_profile_api12 {

         content_by_lua_block {
                 ngx.say("xxxx")
         }
         }


        location @user_profile_api3 {

         content_by_lua_block {
                 ngx.say("hahahah")
         }
        }



lua/dispatch.lua

-------------------------------

local request_method = ngx.var.request_method
local arg=nil
if request_method == "GET" then
         arg = ngx.req.get_uri_args()['params']
elseif request_method == "POST" then
         ngx.req.read_body()
         arg = ngx.req.get_post_args()['params']
end

if arg ~= nil then
   local json = require("cjson")
   local jsonObj = json.decode(arg)
   local profile = jsonObj['query']['user_profile']
   local years = jsonObj['query']['year_id']

  if years ~= nil and profile ~= nil and profile[1] == 'bought_record' then
         ngx.exec('@user_profile_api3') 
   elseif profile ~= nil and profile[1] == 'xubao' then
         ngx.exec('@user_profile_api3')
   else 
         ngx.exec('@user_profile_api12')
   end
end

转载于:https://www.cnblogs.com/maoxiangyi/p/11611383.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值