2021-03-21 08:43:18 +00:00
|
|
|
from sanic import Sanic, response, text
|
2021-11-23 21:00:25 +00:00
|
|
|
from sanic.handlers import ErrorHandler
|
|
|
|
from sanic.server.async_server import AsyncioServer
|
2021-03-21 08:43:18 +00:00
|
|
|
|
|
|
|
|
|
|
|
HTTP_PORT = 9999
|
|
|
|
HTTPS_PORT = 8888
|
|
|
|
|
|
|
|
http = Sanic("http")
|
|
|
|
http.config.SERVER_NAME = f"localhost:{HTTP_PORT}"
|
|
|
|
https = Sanic("https")
|
|
|
|
https.config.SERVER_NAME = f"localhost:{HTTPS_PORT}"
|
|
|
|
|
|
|
|
|
|
|
|
@https.get("/foo")
|
|
|
|
def foo(request):
|
|
|
|
return text("foo")
|
|
|
|
|
|
|
|
|
|
|
|
@https.get("/bar")
|
|
|
|
def bar(request):
|
|
|
|
return text("bar")
|
|
|
|
|
|
|
|
|
|
|
|
@http.get("/<path:path>")
|
|
|
|
def proxy(request, path):
|
|
|
|
url = request.app.url_for(
|
|
|
|
"proxy",
|
|
|
|
path=path,
|
|
|
|
_server=https.config.SERVER_NAME,
|
|
|
|
_external=True,
|
2023-03-16 10:13:17 +00:00
|
|
|
_scheme="https",
|
2021-03-21 08:43:18 +00:00
|
|
|
)
|
|
|
|
return response.redirect(url)
|
|
|
|
|
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
@https.main_process_start
|
2021-03-21 08:43:18 +00:00
|
|
|
async def start(app, _):
|
2021-11-23 21:00:25 +00:00
|
|
|
http_server = await http.create_server(
|
2021-03-21 08:43:18 +00:00
|
|
|
port=HTTP_PORT, return_asyncio_server=True
|
|
|
|
)
|
2021-11-23 21:00:25 +00:00
|
|
|
app.add_task(runner(http, http_server))
|
|
|
|
app.ctx.http_server = http_server
|
|
|
|
app.ctx.http = http
|
2021-03-21 08:43:18 +00:00
|
|
|
|
|
|
|
|
2021-11-23 21:00:25 +00:00
|
|
|
@https.main_process_stop
|
2021-03-21 08:43:18 +00:00
|
|
|
async def stop(app, _):
|
2021-11-23 21:00:25 +00:00
|
|
|
await app.ctx.http_server.before_stop()
|
|
|
|
await app.ctx.http_server.close()
|
|
|
|
for connection in app.ctx.http_server.connections:
|
|
|
|
connection.close_if_idle()
|
|
|
|
await app.ctx.http_server.after_stop()
|
|
|
|
app.ctx.http = False
|
|
|
|
|
|
|
|
|
|
|
|
async def runner(app: Sanic, app_server: AsyncioServer):
|
|
|
|
app.is_running = True
|
|
|
|
try:
|
|
|
|
app.signalize()
|
|
|
|
app.finalize()
|
|
|
|
ErrorHandler.finalize(app.error_handler)
|
|
|
|
app_server.init = True
|
|
|
|
|
|
|
|
await app_server.before_start()
|
|
|
|
await app_server.after_start()
|
|
|
|
await app_server.serve_forever()
|
|
|
|
finally:
|
|
|
|
app.is_running = False
|
|
|
|
app.is_stopping = True
|
2021-03-21 08:43:18 +00:00
|
|
|
|
2023-10-25 00:22:00 +01:00
|
|
|
|
2023-07-05 11:45:08 +01:00
|
|
|
if __name__ == "__main__":
|
|
|
|
https.run(port=HTTPS_PORT, debug=True)
|