我试图让 Nginx
返回一个静态 json 文件,我使用以下方法做到了:
location /health{
default_type "application/json";
alias /etc/health.json;
}
json 文件包含:
{
"status" : "up"
}
我需要做的是找到一种方法,根据响应的内容使用 json 文件返回状态代码。
任何帮助将不胜感激。
谢谢
最佳答案
最简单的做法是运行 nginx 作为反向代理,然后使用某些 Web 服务器返回状态代码。
网络服务器
例如,这是一个执行此操作的简单节点服务器:
const http = require('http');
const fs = require('fs');
const filename = '/path/to/your/file.json';
const server = http.createServer((request, response) => {
fs.readFile(filename, 'utf8', (json) => {
const data = JSON.parse(json);
const statusCode = data.status === 'up' ? 200 : 503;
response.writeHead(status, {"Content-Type": "application/json"});
response.write(json);
});
response.end();
});
const port = process.env.PORT || 3000;
server.listen(port, (e) => console.log(e ? 'Oops': `Server running on http://localhost:${port}`));
Python2 示例(带 flask ):
import json
from flask import Flask
from flask import Response
app = Flask(__name__)
@app.route('/')
def health():
contents = open('health.json').read()
parsed = json.loads(contents)
status = 200 if parsed[u'status'] == u'up' else 503
return Response(
response=contents,
status=status,
mimetype='application/json'
)
如果你连 Flask 都安装不了,那么你可以使用 simplehttpserver 。在这种情况下,您可能最终会自定义 SimpleHTTPRequestHandler 来发送响应。
Nginx 配置
您的 nginx 配置需要包含您的网络服务器的 proxy_pass
location /health {
proxy_set_header Host $host;
proxy_set_header X-REAL-IP $remote_addr;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:3000;
}
您可以在此处查看完整示例:https://github.com/AnilRedshift/yatlab-nginx/blob/master/default.conf
关于json - nginx 返回带有状态码的 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49400679/