环境准备 dockerfile
from fabiocicerchia/nginx-lua:1.25.3-ubuntu22.04
run apt-get -qq update && apt-get -qq install luarocks
run luarocks install lua-cjson
run luarocks install lua-iconv
run luarocks install lua-resty-http
后台代理服务准备(python)
from flask import Flask, jsonify, request
import json
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
@app.route('/test', methods=['POST', 'GET','OPTIONS'])
def hello():
request_data = request.get_json()
print("Request data:", json.dumps(request_data, ensure_ascii=False, indent=4))
data = {
'message': '你好'
}
return jsonify(data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
代码准备
nginx.conf
user nginx;
worker_processes auto;
error_log /dev/stdout;
#error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
lua_package_path "/path/to/lua/?.lua;/another/path/?.lua;;";
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format my escape=json ''
'{ "timestamp": "$time_iso8601", '
'"remote_addr": "$remote_addr",'
'"remote_port":"$remote_port",'
'"costime": "$request_time",'
'"status": "$status",'
'"request_method":"$request_method",'
'"request_uri":"$request_uri",'
'"request_body":"$request_body",'
'"response_body":"$resp_body",'
'"agent": "$http_user_agent" }'
'';
#access_log off;
access_log /dev/stdout my;
#access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65s;
gzip on;
#include /etc/nginx/conf.d/*.conf;
server {
listen 20000;
server_name localhost;
#记录nginx请求返回值
lua_need_request_body on;
set $resp_body "";
body_filter_by_lua '
local resp_body = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end
';
#access_log /var/log/nginx/host.access.log main;
# 该请求测试引入其他位置的lua脚本,access_by_lua_file可以设置多个
# send_track.lua是发送post json 请求的代码
location /test/ {
access_by_lua_file /etc/nginx/workspace/send_track.lua;
proxy_pass http://192.168.2.5:8080/;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
send_track.lua
local http = require("resty.http")
local httpc = http.new()
local res, err = httpc:request_uri("http://192.168.2.5:8080/test", {
method = "POST",
body = '{"key": "这是一个lua请求发送测试"}',
headers = {
["Content-Type"] = "application/json",
["Authorization"] = "Bearer your_token"
}
})
if not res then
ngx.log(ngx.ERR, err)
end
ngx.log(ngx.ERR, res.body)