How to Send a Static Response to the Client in Microgateway

You could use a plugin to conditionally send a static response message back to the client or send the incoming request to the target endpoint defined in the API proxy in Apigee Microgateway as follows:

module.exports.init = function(config, logger, stats) {
    return {
      // indicates start of client request
      onrequest: function(req, res, next) {
        console.log('---> onrequest()');
        next();
      },
      // chunk of request body data received from client
      ondata_request: function(req, res, data, next) {
        console.log('---> ondata_request()');
        next(null, data);
      },
      // last chunk of request body data received from client
      onend_request: function(req, res, data, next) {
        console.log('---> onend_request()');
        if(req.headers['static-response'] == 'true') {
            sendStaticResponse(req, res, data, next);
        }
        else {
            next(null, data);
        }
      },
      // indicates start of target response
      onresponse: function(req, res, next) {
        console.log('---> onresponse()');
        next();
      },
      // a chunk of response body data received from target
      ondata_response: function(req, res, data, next) {
        console.log('---> ondata_response()');
        next(null, data);
      },
      // last chunk of response body data received from target
      onend_response: function(req, res, data, next) {
        console.log('---> onend_response()');
        next(null, data);
      }
   };
}

function sendStaticResponse(req, res, next) {
    var response = {
        type: 'INFO',
        message: 'This is a static response'
    };
    if (!res.finished) res.setHeader('content-type', 'application/json');
    res.end(JSON.stringify(response));
    next(null, response);
}

Example Client Requests

If 'static-response: true' HTTP header is set, above plugin will send the static response message:

curl -i -H 'static-response: true' http://localhost:8000/hello
HTTP/1.1 200 OK
content-type: application/json
Date: Fri, 31 Jul 2020 00:54:18 GMT
Connection: keep-alive
Content-Length: 53
{"type":"INFO","message":"This is a static response"}

If not, it will send the client request to the target endpoint defined in the API proxy:

curl -i http://localhost:8000/hello
HTTP/1.1 200 OK
date: Fri, 31 Jul 2020 00:56:47 GMT
content-type: application/json
...
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Client-Received-Start-Timestamp": "1596157006306",
    "Host": "httpbin.org",
    "Target-Sent-Start-Timestamp": "1596157006312",
    "User-Agent": "curl/7.64.1",
    "X-Amzn-Trace-Id": "Root=1-5f236c4f-03679e14dc0665ba976a6934",
    "X-Forwarded-Host": "localhost:8000"
  },
  "origin": "::ffff:127.0.0.1, ...",
  "url": "https://localhost:8000/get"
}

References

Version history
Last update:
‎07-30-2020 06:49 PM
Updated by: