nginx returns json 状态码文件

nginx returns json file with status code

我正在尝试使 Nginx return 成为一个静态 json 文件,我使用的是:

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

并且 json 文件包含:

{
  "status" : "up"
}

我需要做的是根据响应的内容找到一种方法 return 使用 json 文件的状态代码。

任何帮助将不胜感激。

谢谢

最简单的做法是 运行 nginx 作为反向代理,然后使用一些网络服务器 return 状态代码。

网络服务器

例如,这是一个执行此操作的简单节点服务器:

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 示例(带烧瓶):

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