蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线解析 HTTP/1.1 请求与响应报文、Chunked 十六进制分块编码及 ETag 协商缓存

PYTHONWindows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。explore-http-protocol.py
explore-http-protocol.py171 行
"""Offline network protocol verification lab for Chapter 11 (http-protocol)."""
import json

VERSION = "CPython 3.12.14 offline network protocol frame & state-machine verifier"


def case_http11_request_parser():
    raw_req = (
        b"GET /index.html HTTP/1.1\r\n"
        b"Host: www.example.com\r\n"
        b"User-Agent: Mozilla/5.0\r\n"
        b"Accept: text/html\r\n"
        b"\r\n"
    )
    head, body = raw_req.split(b"\r\n\r\n", 1)
    lines = head.decode("iso-8859-1").split("\r\n")
    method, target, version = lines[0].split(" ", 2)
    headers = {}
    for ln in lines[1:]:
        k, v = ln.split(":", 1)
        headers[k.strip().lower()] = v.strip()

    methods = {"GET": True, "POST": False, "PUT": True, "DELETE": True}  # idempotent flags
    expected = {
        "method": "GET",
        "target": "/index.html",
        "version": "HTTP/1.1",
        "host": "www.example.com",
        "accept": "text/html",
        "body_bytes": 0,
        "idempotent_methods": ["GET", "PUT", "DELETE"],
    }
    actual = {
        "method": method,
        "target": target,
        "version": version,
        "host": headers["host"],
        "accept": headers["accept"],
        "body_bytes": len(body),
        "idempotent_methods": [m for m, idem in methods.items() if idem],
    }
    return {
        "name": "http11_request_parser",
        "summary": "解析 HTTP/1.1 请求行与 Host/User-Agent/Accept 请求头,校验常见请求方法幂等语义",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_http11_response_and_media_types():
    raw_resp = (
        b"HTTP/1.1 200 OK\r\n"
        b"Content-Type: text/html\r\n"
        b"Content-Length: 16\r\n"
        b"\r\n"
        b"<html>...</html>"
    )
    head, body = raw_resp.split(b"\r\n\r\n", 1)
    lines = head.decode("iso-8859-1").split("\r\n")
    ver, code_s, reason = lines[0].split(" ", 2)
    hdrs = {k.strip().lower(): v.strip() for k, v in (ln.split(":", 1) for ln in lines[1:])}

    json_body = json.dumps({"status": "ok"}).encode("utf-8")
    json_ct = "application/json"

    expected = {
        "version": "HTTP/1.1",
        "status_code": 200,
        "reason": "OK",
        "content_type": "text/html",
        "content_length_matches_body": True,
        "json_media_type": "application/json",
        "json_bytes": len(json_body),
    }
    actual = {
        "version": ver,
        "status_code": int(code_s),
        "reason": reason,
        "content_type": hdrs["content-type"],
        "content_length_matches_body": int(hdrs["content-length"]) == len(body),
        "json_media_type": json_ct,
        "json_bytes": len(json_body),
    }
    return {
        "name": "http11_response_and_media_types",
        "summary": "解析 HTTP/1.1 200 OK 响应头与 Content-Type/Content-Length,并验证 text/html 与 application/json 长度匹配",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_http11_chunked_transfer_codec():
    chunks = [b"Hello, ", b"HTTP/1.1 ", b"Chunked!"]
    encoded = b"".join(f"{len(c):x}\r\n".encode("ascii") + c + b"\r\n" for c in chunks) + b"0\r\n\r\n"

    # Decode RFC 9112 chunked body
    pos = 0
    decoded_parts = []
    while True:
        nl = encoded.index(b"\r\n", pos)
        size = int(encoded[pos:nl].decode("ascii"), 16)
        pos = nl + 2
        if size == 0:
            break
        decoded_parts.append(encoded[pos : pos + size])
        pos += size + 2
    decoded = b"".join(decoded_parts).decode("ascii")

    expected = {"chunk_count": 3, "decoded_body": "Hello, HTTP/1.1 Chunked!", "terminated_by_zero_chunk": True}
    actual = {
        "chunk_count": len(decoded_parts),
        "decoded_body": decoded,
        "terminated_by_zero_chunk": encoded.endswith(b"0\r\n\r\n"),
    }
    return {
        "name": "http11_chunked_transfer_codec",
        "summary": "实现 RFC 9112 HTTP/1.1 Transfer-Encoding: chunked 十六进制分块编码与零块终止解码",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_http_cache_and_version_evolution():
    server_etag = '"v2-9f8e7d"'
    cache_control = "public, max-age=3600"
    client_if_none_match = '"v2-9f8e7d"'
    status_on_revalidate = 304 if client_if_none_match == server_etag else 200

    versions = {
        "HTTP/1.0": {"persistent_default": False, "transport": "TCP", "framing": "text"},
        "HTTP/1.1": {"persistent_default": True, "transport": "TCP", "framing": "text"},
        "HTTP/2": {"persistent_default": True, "transport": "TCP", "framing": "binary_multiplexed"},
        "HTTP/3": {"persistent_default": True, "transport": "QUIC/UDP", "framing": "binary_multiplexed"},
    }
    expected = {
        "revalidation_status": 304,
        "max_age_present": True,
        "http2_binary_multiplexed": True,
        "http3_over_quic": True,
    }
    actual = {
        "revalidation_status": status_on_revalidate,
        "max_age_present": "max-age=3600" in cache_control,
        "http2_binary_multiplexed": versions["HTTP/2"]["framing"] == "binary_multiplexed",
        "http3_over_quic": versions["HTTP/3"]["transport"] == "QUIC/UDP",
    }
    return {
        "name": "http_cache_and_version_evolution",
        "summary": "校验 Cache-Control 与 ETag 协商缓存 304 响应及 HTTP/1.0 至 HTTP/3 版本特性演进",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_http11_request_parser(),
        case_http11_response_and_media_types(),
        case_http11_chunked_transfer_codec(),
        case_http_cache_and_version_evolution(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。

入口文件:projects/np-http-protocol-lab/explore-http-protocol.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-http-protocol.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线网络协议帧编解码与状态机验证脚本(纯本地内存执行,未发起外部网络连接)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:网络协议

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a2722.zip

下载课程关联工程包:网络协议

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2727.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习