Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx returns json file with status code

I am trying to make Nginx returns a static json file, and i did that using :

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

and the json file contains :

{
  "status" : "up"
}

What i need to do, is to find a way to return a status code with the json file based on the content of the response.

any help will be appreciated.

Thanks

like image 438
Bara' ayyash Avatar asked May 17 '26 00:05

Bara' ayyash


1 Answers

The simplest thing to do would be to run nginx as a reverse proxy and then use some web server to return the status code.

Webserver

For example, here's a simple node server which does this:

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 example (with 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'
    )

If you can't even install Flask, then you can use simplehttpserver. In that case, you'd probably end up customizing the SimpleHTTPRequestHandler to send your response.

Nginx config

Your nginx config needs to contain a proxy_pass to your webserver

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;
}

You can see a full example here: https://github.com/AnilRedshift/yatlab-nginx/blob/master/default.conf

like image 198
AnilRedshift Avatar answered May 19 '26 15:05

AnilRedshift



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!