File size: 1,355 Bytes
7e8de53
 
 
 
 
 
 
 
 
4639ead
7e8de53
 
 
 
 
4639ead
7e8de53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
43
44
45
46
47
48
49
from fastapi import FastAPI, Request, Response

filenames = ["js/extra.js"]
contents = "\n".join(
    [f"<script type='text/javascript' src='{x}'></script>" for x in filenames]
)

ga_script = """
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-C3VH0S3E6G"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-C3VH0S3E6G');
</script>
"""

app = FastAPI()


@app.middleware("http")
async def insert_js(request: Request, call_next):
    path = request.scope["path"]  # get the request route
    response = await call_next(request)

    if path == "/":
        response_body = ""
        async for chunk in response.body_iterator:
            response_body += chunk.decode()

        charset_tag = '<meta charset="utf-8" />'
        if charset_tag in response_body:
            response_body = response_body.replace(charset_tag, charset_tag + ga_script)

        response_body = response_body.replace("</body>", contents + "</body>")

        del response.headers["content-length"]

        return Response(
            content=response_body,
            status_code=response.status_code,
            headers=dict(response.headers),
            media_type=response.media_type,
        )

    return response