访问 /time 回什么
按简易 HTTP,serve_http 处理 GET /time,响应体是什么?(看 ROUTES)
socket 上的极简 HTTP:请求行形如 GET /path HTTP/1.1。parse_req(raw) 交回 (方法, 路径);build_resp(status, body) 拼「状态行+空行+体」;serve_http(raw) 命中 ROUTES({"/","/time","/echo"}) 回 200、否则 404。
ROUTES = {"/": "hi", "/time": "now", "/echo": "echo"}
def parse_req(raw):
# 取请求行的方法和路径:GET /path HTTP/1.1 -> ("GET", "/path")
line = raw.split(b"\r\n", 1)[0].decode()
method, path, _ = line.split(" ")
return method, path
def build_resp(status, body):
# 拼一个最小 HTTP 响应:状态行 + 空行 + 体
reason = {200: "OK", 404: "Not Found"}.get(status, "OK")
head = "HTTP/1.1 " + str(status) + " " + reason + "\r\n\r\n"
return head.encode() + body.encode()
def serve_http(raw):
# 路由:命中 ROUTES 回 200+内容,否则 404
method, path = parse_req(raw)
if path in ROUTES:
return build_resp(200, ROUTES[path])
return build_resp(404, "no")
resp = serve_http(b"GET /time HTTP/1.1\r\n\r\n")
print(resp.decode().split("\r\n\r\n", 1)[1])
全部评论