I am using openresty to build a simple server.
Upon calling this server, it should make another call to a different server, fetch a JSON result, process it and return the parsed result.
The server should be implemented in openresty for reasons beyond the scope if this question.
error_log /dev/stdout info;
events {
worker_connections 14096;
}
http {
access_log off;
lua_package_path ";;/usr/local/openresty/nginx/?.lua;";
server {
keepalive_requests 100000;
proxy_http_version 1.1;
keepalive_timeout 10;
location / {
content_by_lua_block {
res = ngx.location.capture('http://localhost:8080/functions.json')
ngx.say(res.body)
}
}
location /functions {
root /usr/local/openresty/nginx/html/;
}
listen 0.0.0.0:80 default_server;
}
}
2017/09/11 08:27:49 [error] 7#7: *1 open() "/usr/local/openresty/nginx/htmlhttp://localhost:8080/functions.json" failed (2: No such file or directory), client: 172.17.0.1, server: , request: "GET / HTTP/1.1", subrequest: "http://localhost:8080/functions.json", host: "localhost:8080"
How can I make an HTTP GET request from within a Lua content block in nginx
openresty?
Capture will allow you to capture internal nginx locations and not absolute urls
error_log /dev/stdout info;
events {
worker_connections 14096;
}
http {
access_log off;
lua_package_path ";;/usr/local/openresty/nginx/?.lua;";
server {
keepalive_requests 100000;
proxy_http_version 1.1;
keepalive_timeout 10;
location / {
content_by_lua_block {
res = ngx.location.capture('/functions.json')
ngx.say(res.body)
}
}
location /functions.json {
proxy_pass http://localhost:8080/functions.json;
}
location /functions {
root /usr/local/openresty/nginx/html/;
}
listen 0.0.0.0:80 default_server;
}
}
Solved using the lua-resty-http package. Copied the library to the nginx openresty root, and :
local http = require "resty.http"
local httpc = http.new()
local res, err = httpc:request_uri("http://127.0.0.1/functions.json", { method = "GET" })
// Use res.body to access the response
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With