如何使用Nginx和Lua操作POST请求的JSON主体?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用Nginx和Lua操作POST请求的JSON主体?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1947字,纯文字阅读大概需要3分钟。
内容图文
![如何使用Nginx和Lua操作POST请求的JSON主体?](/upload/InfoBanner/zyjiaocheng/951/7223a8abf35748bcb2426798ca0c0379.jpg)
我正在做一个概念验证,以演示如何在我们的堆栈中实现3scale.在一个示例中,我想做一些POST请求主体操作来创建API外观,该外观将可能是旧API格式的内容映射到新的内部API格式.例如.改变像
{ "foo" : "bar" , "deprecated" : true }
成
{ "FOO" : "bar" }
Lua module docs for content_by_lua,这似乎是适当的方法说
Do not use this directive and other content handler directives in the same location. For example, this directive and the 07002 directive should not be used in the same location.
我的理解是content_by_lua是一个像proxy_pass这样的内容处理程序,每个位置只能使用其中一个.
我不认为有任何方法可以删除proxy_pass,因为这是代理工作方式的基础,因此可以在单独的位置捕获请求,使用content_by_lua,然后传递到实现proxy_pass的位置,或者是否有不同的方法,如rewrite_by_lua哪个更合适?
如果它对其他人有帮助,我添加了以下函数(我的第一个Lua),它删除了3scale需要授权的user_key参数,但如果转发到我们的API则无效:
function remove_user_key()
ngx.req.read_body()
-- log the original body so we can compare to the new one later
local oldbody = ngx.req.get_body_data()
log(oldbody)
-- grab the POST parameters as a table
local params = ngx.req.get_post_args()
-- build up the new JSON string
local newbody = "{"
for k,v in pairs(params) do
-- add all the params we want to keep
if k ~= "user_key" then
log("adding"..k.." as "..v)
newbody = newbody..'"'..k..'":"'..v..'",'
else
log("not adding user_key")
end
end
--remove the last trailing comma before closing this off
newbody = string.sub(newbody, 0, #newbody-1)
newbody = newbody.."}"
ngx.req.set_body_data(newbody)
log(newbody)
end
if ngx.req.get_method() == "POST" then
remove_user_key()
end
解决方法:
我建议你使用access_by_lua
在nginx.conf中
location / { #host and port to fastcgi server default_type text/html; set $URL "http://$http_host$request_uri"; access_by_lua_file /home/lua/cache.lua; proxy_pass http://$target; ------- ---------
在cache.lua文件中,您可以执行以下操作:
if ngx.req.get_method() == "POST" then -- check if request method is POST -- implement your logic return end
内容总结
以上是互联网集市为您收集整理的如何使用Nginx和Lua操作POST请求的JSON主体?全部内容,希望文章能够帮你解决如何使用Nginx和Lua操作POST请求的JSON主体?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。