🙆‍♀️

【Python 3】hpack で HTTP/2 ヘッダーを圧縮する

2024/04/26に公開

HTTP/2 クライアントの Hyper のもとで開発されている hpack を使って HTTP/2 ヘッダーを圧縮してみよう。Debian の場合、システム全体で利用するには python3-hpack を導入する

sudo apt install python3-hpack

コードを書いてみる

# https://github.com/python-hyper/hpack/blob/master/test/test_hpack.py

from hpack import (
    Encoder,
    Decoder
)

header_set = [
  (':method', 'GET', True),
  (':path', '/jimiscool/', True),
  ('customkey', 'sensitiveinfo', True)
]

header_set2 = [
  (':method', 'GET'),
  (':path', '/jimiscool/'),
  ('customkey', 'sensitiveinfo')
]

result = (b'\x82\x14\x88\x63\xa1\xa9' +
          b'\x32\x08\x73\xd0\xc7\x10' +
          b'\x87\x25\xa8\x49\xe9\xea' +
          b'\x5f\x5f\x89\x41\x6a\x41' +
          b'\x92\x6e\xe5\x35\x52\x9f')

e = Encoder()
d = Decoder()
assert e.encode(header_set, huffman=True) == result
assert d.decode(result) == header_set2

Discussion