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

# ----- 片段 1 (bash) -----
curl -i https://www.example.com/

# ----- 片段 2 (bash) -----
# 提交表单数据
curl -X POST https://httpbin.org/post \
  -d "name=codelab&level=beginner"

# 更常见的做法:提交 JSON
curl -X POST https://httpbin.org/post \
  -H "Content-Type: application/json" \
  -d '{"name": "codelab", "level": "beginner"}'

# ----- 片段 3 (bash) -----
# PUT:整体替换资源
curl -X PUT https://httpbin.org/put \
  -H "Content-Type: application/json" \
  -d '{"id": 1, "name": "renamed"}'

# DELETE:删除资源,响应体通常是空的
curl -i -X DELETE https://httpbin.org/delete

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

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/old":
            self.send_response(301)                 # 永久重定向
            self.send_header("Location", "/")       # 告诉浏览器新地址
            self.end_headers()
        elif self.path == "/missing":
            self.send_response(404)                 # 资源不存在
            self.end_headers()
            self.wfile.write(b"not found")
        else:
            self.send_response(200)                 # 正常返回
            self.end_headers()
            self.wfile.write(b"hello")

    def log_message(self, *args):
        pass  # 关掉默认日志,保持输出干净

server = HTTPServer(("127.0.0.1", 0), Handler)      # 端口 0 = 随机空闲端口
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()

for path in ["/", "/old", "/missing"]:
    conn = http.client.HTTPConnection("127.0.0.1", port, timeout=3)
    conn.request("GET", path)
    resp = conn.getresponse()
    print(path, "->", resp.status, resp.reason,
          "| Location:", resp.getheader("Location"))
    conn.close()

server.shutdown()

# ----- 片段 5 (text) -----
/ -> 200 OK | Location: None
/old -> 301 Moved Permanently | Location: /
/missing -> 404 Not Found | Location: None

# ----- 片段 6 (bash) -----
# 把第 5 节的服务器端口改成固定的 8000 运行,然后:
# -o /dev/null 丢弃响应体,-w 自定义输出格式
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8000/
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8000/missing
