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
相关推荐
w我是东山啊5 分钟前
ARP的具体过程和ARP欺骗
linux·服务器·网络
闲人编程5 分钟前
GraphQL与REST API对比与实践
后端·python·api·graphql·rest·codecapsule
街灯L19 分钟前
【Ubuntu】安装配置nginx文件版
服务器·nginx·ubuntu
winfredzhang25 分钟前
深入剖析 wxPython 配置文件编辑器
python·编辑器·wxpython·ini配置
HIT_Weston28 分钟前
53、【Ubuntu】【Gitlab】拉出内网 Web 服务:http.server 单/多线程分析(五)
网络协议·http·gitlab
多恩Stone33 分钟前
【3DV 进阶-9】Hunyuan3D2.1 中的 MoE
人工智能·pytorch·python·算法·aigc
爱打代码的小林35 分钟前
网络爬虫基础
爬虫·python
B站计算机毕业设计之家36 分钟前
大数据项目:基于python电商平台用户行为数据分析可视化系统 电商订单数据分析 Django框架 Echarts可视化 大数据技术(建议收藏)
大数据·python·机器学习·数据分析·django·电商·用户分析
weixin_4215850138 分钟前
静态图(Static Graph) vs 动态执行(Eager Execution)
python
阿巴~阿巴~43 分钟前
HTTP服务器实现请求解析与响应构建:从基础架构到动态交互
服务器·网络·网络协议·http·交互·请求解析·响应构建