A middleware that encodes in json the response body in case
    of that the "Content-Type" header is "application/json".

    This middlware accepts and optional `encoder` parameter, that
    allow to the user specify its own json encoder class.

def wrap_json_response(func=None, *, encoder=json.JSONEncoder):
    """
    A middleware that encodes in json the response body in case
    of that the "Content-Type" header is "application/json".

    This middlware accepts and optional `encoder` parameter, that
    allow to the user specify its own json encoder class.
    """

    if func is None:
        return functools.partial(wrap_json_response, encoder=encoder)

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        response = func(request, *args, **kwargs)

        if "Content-Type" in response.headers and response.headers['Content-Type'] is not None:
            ctype, pdict = parse_header(response.headers.get('Content-Type', ''))
            if ctype == "application/json" and (isinstance(response.body, dict) or isinstance(response.body, list)):
                response.body = json.dumps(response.body, cls=encoder)
        return response

    return wrapper