How to replace flow.resposne.content to utf-8 in add-on script?

Steps to reproduce the problem:

Hi experts,
i’m trying to use the mitmweb to work as the front view to watch the network traffic.
but when i was trying to replace the response.content, it said message content must be bytes.
i tried to encode the string, but on the web it displays bytes (\x56, i.e.) not real utf-8 string, what should i do?

  1. create an add-on script
  2. load it
  3. by using this command:
    mitmweb --listen-port 443 --web-port 80 --no-web-open-browser --web-iface 0.0.0.0 -s rule.py
  4. using this script

import mitmproxy.http
from mitmproxy import ctx
class Rule:
def response(self, flow: mitmproxy.http.HTTPFlow):
if ‘xxx’ in flow.request.url:
with open(‘5dfe8190-ee68-11e8-a251-6901d85114ca’) as f:
flow.response.content = f.read().encode(‘utf-8’).decode(‘utf-8’)
addons = [
Rule()
]
actual it tell me:
Addon error: Traceback (most recent call last):
File “rule.py”, line 8, in response
flow.response.content = f.read().encode(‘utf-8’).decode(‘utf-8’)
File “mitmproxy/net/http/message.py”, line 115, in set_content
TypeError: Message content must be bytes, not str. Please use .text if you want to assign a str.

Response object has various property, you are trying to modify the content that is byte as you verify. If you want to set response as string you can assign value to flow.response.text then mitmproxy will take care to encode properly as header says.