json - nginx 返回带有状态码的 json 文件

标签 json nginx http-status-codes

我试图让 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/

相关文章:

rest - 如果客户端没有指定大集合的范围,REST 服务应该返回什么

json - 错误 403(禁止):Your client does not have permission to get URL

ssl - web端如何实现Https面向nginx及其背后的几个微服务

rest - 当不支持 HTTP 方法时向客户端发送消息

rest - 无法处理请求的 HTTP 状态码

nginx - GitLab Mattermost 中的 400 Bad Request

java - 如何使用 java sdk 将嵌套的 json 对象存储和更新到 couchbase

c# - 通过仅显示特定字段来格式化 JSON 输出

javascript - 无法从 php 获取 json 到 html(有时有效,有时无效..)

perl - Starman 的最佳 --max-requests 设置是什么?