OpenResty 中使用 ngx.location.capture 完成第三方接口请求

OpenResty Lua About 1,059 words

方法介绍

OpenResty自带方法,同步但非阻塞的Nginx子请求,模拟HTTP但没有额外的HTTP/TCP流量和IPC调用。

文档地址:https://github.com/openresty/lua-nginx-module#ngxlocationcapture

特别注意

  • 不能使用location @name配置方式;
  • 使用internal指令限制只能内部方法;
  • body参数只能使用string(可结合cjson完成application/json请求);
  • gzip后的请求不能被Lua正常解析,关闭转发header,设置proxy_pass_request_headersoff
  • ngx.timer中不能使用;

快速入门

此处只介绍作为HTTP客户端请求第三方接口的情况,用于内部之请求的情况,请查阅官方文档

Nginx配置

location = /api {
    internal;
    set_by_lua $target 'return ngx.ctx.target_uri';
    proxy_pass_request_headers off;
    proxy_pass $target;
}

GET请求

使用ngx.encode_args对参数进行urlencode

local args = {
    page = 1,
    size = 20
}

local res = ngx.location.capture('/api', {
    method = ngx.HTTP_GET,
    ctx = {
        target_uri = "http://127.0.0.1?" .. ngx.encode_args(args),
    }
})

POST请求

application/json示例

local req_param = json.encode({
    postId = 304
})
local res = ngx.location.capture('/api', {
    method = ngx.HTTP_POST,
    body = req_param,
    ctx = {
        target_uri = "http://127.0.0.1/post/random",
    }
})

开源案例

https://github.com/fendoudebb/z-blog-openresty

Views: 10,265 · Posted: 2020-03-02

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh