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
相关推荐
jasnet_u4 小时前
centos7扩展磁盘并新建分区
linux·运维·服务器
源远流长jerry5 小时前
浏览器的同源策略
服务器·http·okhttp
威风的虫5 小时前
RAG 系统的经典工作流程
人工智能·python·rag
棒棒的皮皮6 小时前
【深度学习】YOLO-Python基础认知与算法演进
python·深度学习·yolo·计算机视觉
aiguangyuan6 小时前
机器学习入门
人工智能·python·机器学习
oMcLin6 小时前
Linux服务器出现“Out of Memory”错误,如何通过调整swap、hugepages等配置来缓解内存压力
linux·服务器·jenkins
Psycho_MrZhang7 小时前
高并发服务设计思路
python
liulilittle7 小时前
CLANG 交叉编译
linux·服务器·开发语言·前端·c++
多米Domi0117 小时前
0x3f 第21天 三更java进阶1-35 hot100普通数组
java·python·算法·leetcode·动态规划
小程故事多_807 小时前
从零吃透PyTorch,最易懂的入门全指南
人工智能·pytorch·python