Skip to content

Instantly share code, notes, and snippets.

@jazzyjackson
Created April 13, 2023 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jazzyjackson/9c6b86f47cc7320479f5516507b89111 to your computer and use it in GitHub Desktop.
Save jazzyjackson/9c6b86f47cc7320479f5516507b89111 to your computer and use it in GitHub Desktop.
import asyncio
from fastapi import FastAPI, WebSocket
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
import os
import websockets
app = FastAPI()
# Mount the static files in the storage/node_modules/gun directory under the /gun path
app.mount("/gun", StaticFiles(directory="storage/node_modules/gun"), name="gun")
@app.get("/")
async def get_index():
# Serve the index.html file at the root path
return FileResponse("index.html")
@app.websocket("/gun/ws")
async def gun_websocket_proxy(websocket: WebSocket):
gun_ws_uri = "ws://localhost:8765/gun"
async with websockets.connect(gun_ws_uri) as gun_websocket:
await websocket.accept()
async def forward_client_to_gun():
try:
while True:
message = await websocket.receive_text()
await gun_websocket.send(message)
except:
pass
async def forward_gun_to_client():
try:
while True:
message = await gun_websocket.recv()
await websocket.send_text(message)
except:
pass
await asyncio.gather(forward_client_to_gun(), forward_gun_to_client())
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment