Python实现一个简单的 HTTP echo 服务器

一个用来做测试的简单的 HTTP echo 服务器。

python 复制代码
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

class EchoHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # 构造响应数据
        response_data = {
            'path': self.path,
            'method': 'GET',
            'headers': dict(self.headers),
            'query_string': self.path.split('?')[1] if '?' in self.path else ''
        }
        
        # 设置响应头
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        
        # 发送响应
        self.wfile.write(json.dumps(response_data, indent=2).encode())
    
    def do_POST(self):
        # 获取请求体长度
        content_length = int(self.headers.get('Content-Length', 0))
        # 读取请求体
        body = self.rfile.read(content_length).decode()
        
        # 构造响应数据
        response_data = {
            'path': self.path,
            'method': 'POST',
            'headers': dict(self.headers),
            'body': body
        }
        
        # 设置响应头
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        
        # 发送响应
        self.wfile.write(json.dumps(response_data, indent=2).encode())

def run_server(port=8000):
    server_address = ('', port)
    httpd = HTTPServer(server_address, EchoHandler)
    print(f'Starting server on port {port}...')
    httpd.serve_forever()

if __name__ == '__main__':
    run_server()

这个 HTTP echo 服务器的特点:

  1. 支持 GET 和 POST 请求
  2. 返回 JSON 格式的响应
  3. 对于 GET 请求,会返回:
    • 请求路径
    • 请求方法
    • 请求头
    • 查询字符串
  4. 对于 POST 请求,额外返回请求体内容

使用方法:

  1. 运行脚本启动服务器
  2. 使用浏览器或 curl 访问 http://localhost:8000

测试示例:

bash 复制代码
# GET 请求
curl http://localhost:8000/test?foo=bar

# POST 请求
curl -X POST -d "hello=world" http://localhost:8000/test
相关推荐
白总Server12 分钟前
多智能体系统的中间件架构
linux·运维·服务器·中间件·ribbon·架构·github
GeekABC1 小时前
FastAPI系列06:FastAPI响应(Response)
开发语言·python·fastapi·web
fen_fen1 小时前
Python3:Jupyter Notebook 安装和配置
ide·python·jupyter
float_六七2 小时前
Python语言基础知识详解:分支结构控制语句
python
声声codeGrandMaster2 小时前
django之优化分页功能(利用参数共存及封装来实现)
数据库·后端·python·django
Johny_Zhao2 小时前
OpenStack 全套搭建部署指南(基于 Kolla-Ansible)
linux·python·信息安全·云计算·openstack·shell·yum源·系统运维
2401_867021902 小时前
文件缓冲区(IO与文件 ·III)(linux/C)
linux·运维·服务器·c语言
27669582922 小时前
海关 瑞数 后缀分析 rs
java·python·rs·瑞数·海关·瑞数后缀·后缀生成
学c真好玩3 小时前
Django创建的应用目录详细解释以及如何操作数据库自动创建表
后端·python·django
沐暖沐3 小时前
Django(快速上手版)
python·django