python
主页 > 脚本 > python >

Python如何实现HTTP echo服务器

2025-01-07 | 佚名 | 点击:

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

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

2

3

4

# GET 请求

curl http://localhost:8000/test?foo=bar

# POST 请求

curl -X POST -d "hello=world" http://localhost:8000/test

原文链接:
相关文章
最新更新