Camp

Http Static Server

Posted at — Apr 26, 2020

只使用标准库,用 socket 完成 HTTP 静态文件服务器,实现如下功能:

  1. 下载文件

    1. 文件不存在的时候报 404

    2. 文件存在直接返回文件内容

    3. 支持 Range 下载功能 (加分)

  2. 上传文件

    1. 可以指定文件保存的路径

    2. 指定路径存在文件的时候报错


CWD 目录结构如下

.
├── a.txt
└── dir
   └── b.txt
  • 执行

    curl http://localhost:8080/a.txt

    返回 a.txt 的文件内容

  • 执行

    curl http://localhost:8080/dir/b.txt

    返回 dir/b.txt 的文件内容

  • 执行

    curl http://localhost:8080/dir2/a.txt

    返回 404。

  • 执行

    curl -X POST -F "file=@/path/to/test.jpg" \
        -H "Content-Type: multipart/form-data" \
        http://localhost:8080/test.jpg

    返回 200

    {
      "status": "ok",
      "url": "http://localhost:8080/test.jpg"
    }
  • 执行

    curl -X POST -F "file=@/path/to/b.txt" \
        -H "Content-Type: multipart/form-data" \
        http://localhost:8080/dir/b.txt

    返回 400

    {
      "status": "error",
      "msg": "file exists"
    }