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
相关推荐
java1234_小锋1 分钟前
TensorFlow2 Python深度学习 - 循环神经网络(SimpleRNN)示例
python·深度学习·tensorflow·tensorflow2
java1234_小锋2 分钟前
TensorFlow2 Python深度学习 - 通俗理解池化层,卷积层以及全连接层
python·深度学习·tensorflow·tensorflow2
软件技术员6 分钟前
使用ACME自动签发SSL 证书
服务器·网络协议·ssl
fsnine13 分钟前
Python图形化界面——pyqt5教程
开发语言·python·qt
Murphy_lx26 分钟前
Linux系统--信号(4--信号捕捉、信号递达)陌生概念篇
linux·运维·服务器
Asuncion00733 分钟前
Docker核心揭秘:轻量级虚拟化的革命
服务器·开发语言·docker·云原生
扶尔魔ocy1 小时前
python程序打包成win的exe应用(以OCR应用为例)
python·ocr·中文识别
焱焱枫1 小时前
Linux疑难杂症诊断利器:深入解析 fuser 命令
linux·运维·服务器
Psycho_MrZhang1 小时前
自定义层和读写文件
pytorch·python·深度学习
Andya_net1 小时前
Java | 基于redis实现分布式批量设置各个数据中心的服务器配置方案设计和代码实践
java·服务器·分布式