NGINX read body from proxy_pass response

前端 未结 2 1682
鱼传尺愫
鱼传尺愫 2021-01-18 01:06

I have two servers:

  1. NGINX (it exchanges file id to file path)
  2. Golang (it accepts file id and return it\'s path)

Ex: Wh

2条回答
  •  野的像风
    2021-01-18 01:39

    Looks like you are wanting to make an api call for data to run decision and logic against. That's not quite what proxying is about.

    The core proxy ability of nginx is not designed for what you are looking to do.

    Possible workaround: extending nginx...


    Nginx + PHP

    Your php code would do the leg work.
    Serve as a client to connect to the Golang server and apply additional logic to the response.

    
    
        location /getpath {
            try_files /getpath.php;
        }
    

    This is just the pseudo-code example to get it rolling.

    Some miscellaneous observations / comments:

    • The Golang response doesn't look like valid json, replace preg_match_all with json_decode if so.
    • readfile is not super efficient. Consider being creative with a 302 response.

    Nginx + Lua

    sites-enabled:

    lua_package_path "/etc/nginx/conf.d/lib/?.lua;;";
    
    server {
        listen 80 default_server;
        listen [::]:80 default_server;
    
        location /getfile {
            root /var/www/html;
            resolver 8.8.8.8;
            set $filepath "/index.html";
            access_by_lua_file /etc/nginx/conf.d/getfile.lua;
            try_files $filepath =404;
        }
    }
    
    

    Test if lua is behaving as expected:

    getfile.lua (v1)

      ngx.var.filepath = "/static/...";
    

    Simplify the Golang response body to just return a bland path then use it to set filepath:

    getfile.lua (v2)

    local http = require "resty.http"
    local httpc = http.new()
    local query_string = ngx.req.get_uri_args()
    local res, err = httpc:request_uri('https://go.example.com/getpath?file_id=' .. query_string["id"], {
        method = "GET",
        keepalive_timeout = 60,
        keepalive_pool = 10
    })
    
    if res and res.status == ngx.HTTP_OK then
        body = string.gsub(res.body, '[\r\n%z]', '')
        ngx.var.filepath = body;
        ngx.log(ngx.ERR, "[" .. body .. "]");
    else
        ngx.log(ngx.ERR, "missing response");
        ngx.exit(504);
    end
    

    resty.http

    mkdir -p /etc/nginx/conf.d/lib/resty
    wget "https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http_headers.lua" -P /etc/nginx/conf.d/lib/resty
    wget "https://raw.githubusercontent.com/ledgetech/lua-resty-http/master/lib/resty/http.lua" -P /etc/nginx/conf.d/lib/resty
    

提交回复
热议问题