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

#!/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]


    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"


if __name__ == "__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
hoverctl mode simulate
hoverctl middleware --binary python --script
curl --proxy http://localhost:8500
hoverctl stop

As you can see, middleware allows you to completely modify the content of a simulated HTTP response.