|
| 1 | +# dummy_caddy_like_server.py |
| 2 | +from fastapi import FastAPI, Request, HTTPException |
| 3 | +from fastapi.responses import ( |
| 4 | + JSONResponse, |
| 5 | + HTMLResponse, |
| 6 | + PlainTextResponse, |
| 7 | + FileResponse, |
| 8 | +) |
| 9 | +from pathlib import Path |
| 10 | +import stat |
| 11 | + |
| 12 | +ROOT = Path("./").resolve() |
| 13 | +ROOT.mkdir(exist_ok=True) |
| 14 | + |
| 15 | +app = FastAPI() |
| 16 | + |
| 17 | + |
| 18 | +def safe_path(req_path: str) -> Path: |
| 19 | + p = (ROOT / req_path).resolve() |
| 20 | + if not p.is_relative_to(ROOT): |
| 21 | + raise HTTPException(status_code=403) |
| 22 | + return p |
| 23 | + |
| 24 | + |
| 25 | +def list_dir(path: Path): |
| 26 | + entries = [] |
| 27 | + for p in sorted(path.iterdir()): |
| 28 | + st = p.stat() |
| 29 | + entries.append({ |
| 30 | + "name": p.name, |
| 31 | + "type": "directory" if p.is_dir() else "file", |
| 32 | + "size": st.st_size if p.is_file() else 0, |
| 33 | + "mtime": int(st.st_mtime), |
| 34 | + "mode": stat.filemode(st.st_mode), |
| 35 | + }) |
| 36 | + return entries |
| 37 | + |
| 38 | + |
| 39 | +@app.get("/{req_path:path}") |
| 40 | +async def browse(req_path: str, request: Request): |
| 41 | + fs_path = safe_path(req_path) |
| 42 | + |
| 43 | + if not fs_path.exists(): |
| 44 | + raise HTTPException(status_code=404) |
| 45 | + |
| 46 | + # ---- FILE DOWNLOAD (binary-safe) ---- |
| 47 | + if fs_path.is_file(): |
| 48 | + return FileResponse( |
| 49 | + fs_path, |
| 50 | + filename=fs_path.name, |
| 51 | + media_type="application/octet-stream", |
| 52 | + ) |
| 53 | + |
| 54 | + # ---- DIRECTORY ---- |
| 55 | + # index.html suppresses listing |
| 56 | + index = fs_path / "index.html" |
| 57 | + if index.exists(): |
| 58 | + return HTMLResponse(index.read_text()) |
| 59 | + |
| 60 | + accept = request.headers.get("accept", "") |
| 61 | + entries = list_dir(fs_path) |
| 62 | + |
| 63 | + if "application/json" in accept: |
| 64 | + return JSONResponse(entries) |
| 65 | + |
| 66 | + if "text/plain" in accept: |
| 67 | + return PlainTextResponse("\n".join(e["name"] for e in entries)) |
| 68 | + |
| 69 | + # default HTML |
| 70 | + html = "<ul>" + "".join( |
| 71 | + f"<li><a href='{e['name']}'>{e['name']}</a></li>" |
| 72 | + for e in entries |
| 73 | + ) + "</ul>" |
| 74 | + return HTMLResponse(html) |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == "__main__": |
| 78 | + import uvicorn |
| 79 | + uvicorn.run(app, host="0.0.0.0", port=8000) |
0 commit comments