Nginx 返回带有状态码的 JSON 文件。

3

我正在尝试让Nginx返回一个静态的json文件,我使用了以下方式:

location /health{
   default_type "application/json";
   alias /etc/health.json;
}

并且json文件包含:

{
  "status" : "up"
}

我需要做的是找到一种方式,在响应内容的基础上返回JSON文件的状态码。任何帮助将不胜感激。谢谢。

在返回状态为“已启动”或“已停止”之前,我需要进行一些逻辑处理。 - Bara' ayyash
可能是为什么nginx返回带有状态码的JSON文件的重复问题。 - Igor Cova
1
这是我的问题的副本 - Bara' ayyash
1个回答

2
最简单的做法是将nginx作为反向代理运行,然后使用某个Web服务器返回状态代码。
Web服务器
例如,这里有一个简单的Node服务器来实现此功能:
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配置需要包含一个代理传递到您的Web服务器。

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

感谢您的帮助,我考虑过这个问题,但是我的虚拟机上没有任何服务器,只有nginx。 - Bara' ayyash
甚至不用Python 2吗?许多编程语言都有内置的Web服务器或易于使用的库。 - AnilRedshift
你可以将请求转发到任何你控制的URL,它不必在同一台服务器上。 - AnilRedshift
我有Python Python2,你能否请修改你的代码以匹配Python2? - Bara' ayyash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接