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
相关推荐
Yukinaaaa4 分钟前
以“轮盘数组”思维彻底搞懂并实现阻塞队列
java·服务器·ide·安全·javaee·阻塞队列·轮盘数组
留白_6 分钟前
pandas文件读取与存储
开发语言·python·pandas
我的xiaodoujiao8 分钟前
API 接口自动化测试详细图文教程学习系列25--继续处理testCase中的数据
python·学习·测试工具·pytest
Wang ruoxi11 分钟前
Pygame 小游戏——节奏点击
python·pygame
夕除13 分钟前
AOP 实现 Redis 缓存切面解析
java·开发语言·python
fanjiu202020 分钟前
python查询nightingale监控
python
TechWayfarer30 分钟前
IP画像在企业安全中的应用:它能做什么?不能替代什么
网络·python·tcp/ip·安全·网络安全
HLC++41 分钟前
Linux文件操作
linux·运维·服务器
Rauser Mack44 分钟前
不懂编程,但是vibe coding一个扫雷游戏
人工智能·python·游戏·html·prompt
晚风予卿云月1 小时前
【Linux】进程控制(二)——进程等待 全方位详解
linux·运维·服务器·进程控制·进程等待