# ===== CodeLab: net-cache =====
# 以下代码片段按文章出现顺序拼接, 共 6 段

# ----- 片段 1 (bash) -----
# -I 只取响应头,不下载响应体
curl -I https://httpbin.org/cache/60

# ----- 片段 2 (python) -----
import hashlib
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import http.client

BODY = b"<html>hello cache</html>"
ETAG = hashlib.md5(BODY).hexdigest()

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        inm = self.headers.get("If-None-Match")
        if inm == ETAG:
            # 内容没变:返回 304,不带响应体
            self.send_response(304)
            self.end_headers()
            return
        self.send_response(200)
        self.send_header("Cache-Control", "max-age=10")  # 强缓存 10 秒
        self.send_header("ETag", ETAG)                   # 协商缓存指纹
        self.end_headers()
        self.wfile.write(BODY)

    def log_message(self, *args):
        pass

server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()

# 第一次请求:200,拿到 ETag
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=3)
conn.request("GET", "/")
r1 = conn.getresponse()
etag = r1.getheader("ETag")
print("第一次:", r1.status, "| Cache-Control:", r1.getheader("Cache-Control"))
conn.close()

# 第二次请求:带上 If-None-Match 协商,命中返回 304
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=3)
conn.request("GET", "/", headers={"If-None-Match": etag})
r2 = conn.getresponse()
print("第二次(带 If-None-Match):", r2.status, "| 响应体长度:", len(r2.read()))
conn.close()

server.shutdown()

# ----- 片段 3 (bash) -----
# 第一次:200,响应头里能看到 ETag 和 Cache-Control
curl -i http://127.0.0.1:8000/

# 把上一步 ETag 的值填进来:命中协商缓存,返回 304
curl -i -H 'If-None-Match: <第一次响应里的ETag值>' http://127.0.0.1:8000/

# ----- 片段 4 (text) -----
<link rel="stylesheet" href="/static/app.a1b2c3.css">
<script src="/static/main.9f8e7d.js"></script>

# ----- 片段 5 (bash) -----
# 静态资源:长缓存
location /static/ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

# HTML 入口:每次都协商
location / {
    add_header Cache-Control "no-cache";
}

# ----- 片段 6 (bash) -----
curl -i -H 'Cache-Control: no-cache' http://127.0.0.1:8000/
