Using middleware to modify response payload and status codeΒΆ
See also
Please carefully read through Middleware alongside these tutorials to gain a high-level understanding of what we are about to cover.
We will use a python script to modify the body of a response and randomly change the status code.
Let’s begin by writing our middleware. Save the following as middleware.py
:
#!/usr/bin/env python
import sys
import json
import logging
import random
logging.basicConfig(filename='middleware.log', level=logging.DEBUG)
logging.debug('Middleware "modify_request" called')
def main():
payload = sys.stdin.readlines()[0]
logging.debug(payload)
payload_dict = json.loads(payload)
payload_dict['response']['status'] = random.choice([200, 201])
if "response" in payload_dict and "body" in payload_dict["response"]:
payload_dict["response"]["body"] = "{'foo': 'baz'}\n"
print(json.dumps(payload_dict))
if __name__ == "__main__":
main()
The middleware script randomly toggles the status code between 200 and 201, and changes the response body to a dictionary containing {'foo':'baz'}
.
hoverctl start
hoverctl mode capture
curl --proxy http://localhost:8500 http://time.jsontest.com
hoverctl mode simulate
hoverctl middleware --binary python --script middleware.py
curl --proxy http://localhost:8500 http://time.jsontest.com
hoverctl stop
As you can see, middleware allows you to completely modify the content of a simulated HTTP response.