Skip to content

Commit

Permalink
Merge pull request #20 from googleanalytics/deno-serve-fix
Browse files Browse the repository at this point in the history
refactored serveHttp to use serve and updated Eta to latest version
  • Loading branch information
matt-landers authored May 13, 2024
2 parents f69a737 + 8f9e49f commit d766dd4
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 164 deletions.
74 changes: 29 additions & 45 deletions src/deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

86 changes: 36 additions & 50 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,60 +1,46 @@
import { configure, renderFile } from "https://deno.land/x/eta@v1.11.0/mod.ts";
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import { Eta } from "https://deno.land/x/eta@v3.0.3/src/index.ts";
import { parseArgs } from "jsr:@std/cli/parse-args";

const __dirname = new URL(".", import.meta.url).pathname;

const viewPath = [
`${__dirname}/public`,
`${__dirname}/public/partials`,
`${__dirname}/public/layouts`,
];
const viewpath = Deno.cwd() + "/src/public/";
const eta = new Eta({ views: viewpath, cache: true });

configure({ views: viewPath });
const flags = parse(Deno.args, {
string: [ "port" ],
default: { port: 80 },
const flags = parseArgs(Deno.args, {
string: ["port"],
default: { port: "3000" },
});

const server = Deno.listen({ port: flags.port });

console.log("File server running on http://localhost:" + flags.port + "/");

for await (const conn of server) {
handleHttp(conn).catch(console.error);
}

async function handleHttp(conn: Deno.Conn) {
const httpConn = Deno.serveHttp(conn);
for await (const requestEvent of httpConn) {
const url = new URL(requestEvent.request.url);
let filepath = decodeURIComponent(url.pathname);
if (filepath === "/") {
filepath = "index.eta";
} else if (filepath.toLocaleLowerCase().indexOf(".") <= 0) {
filepath = `${filepath}.eta`;
}
async function handler(request: Request) {
const url = new URL(request.url);
let filepath = decodeURIComponent(url.pathname);
if (filepath === "/") {
filepath = "/index.eta";
} else if (filepath.toLocaleLowerCase().indexOf(".") <= 0) {
filepath = `${filepath}.eta`;
}

let file;
let response;
try {
console.log(filepath);
if (filepath.indexOf(".eta") > 0) {
response = new Response(await renderFile(filepath, {}), {
headers: { "content-type": "text/html" },
});
} else {
file = await Deno.open(__dirname + "public" + filepath, {
read: true,
});
const readableStream = file.readable;
response = new Response(readableStream);
}
} catch (e) {
console.error(e);
response = new Response("404 Not Found", { status: 404 });
return;
let file;
let response;
try {
console.log(filepath);
if (filepath.indexOf(".eta") > 0) {
response = new Response(await eta.render(filepath, {}), {
headers: { "content-type": "text/html" },
});
} else {
file = await Deno.open(__dirname + "public" + filepath, {
read: true,
});
const readableStream = file.readable;
response = new Response(readableStream);
}

await requestEvent.respondWith(response);
} catch (e) {
console.error(e);
response = new Response("404 Not Found", { status: 404 });
}

return response;
}

Deno.serve({ port: parseInt(flags.port) }, handler);
21 changes: 8 additions & 13 deletions src/public/about.eta
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
<% layout("layout", { title: "About - GA Tutorials" }) %>
<%~ includeFile("nav") %>
<% layout("./layouts/layout", { title: "About - GA Tutorials" }) %>

<%~ include("./partials/nav") %>

<main class="container-lg pt-3 pb-5">
<h1 class="pt-4 pb-2">About the tutorial series</h1>
<a class="twitter-share-button" target="_blank"
href="https://twitter.com/intent/tweet?text=%23HelloAnalytics%20%23GA4TutorialSeries">
<a class="twitter-share-button" target="_blank" href="https://twitter.com/intent/tweet?text=%23HelloAnalytics%20%23GA4TutorialSeries">
<span>Tweet</span></a>
<div class="pt-4 content-width">
<p>The Google Analytics 4 Tutorials series is a collection of videos created by the Google Analytics team to
Expand All @@ -14,19 +13,15 @@
using advanced features like ecommerce and user ID.</p>
<p>All the videos in the series can be found on the
<a href="https://www.youtube.com/channel/UCJ5UyIAa5nEGksjcdp43Ixw" target="_blank">Google
Analytics YouTube channel</a>, in the <a
href="https://youtube.com/playlist?list=PLI5YfMzCfRtZ4bHJJDl_IJejxMwZFiBwz" target="_blank">Google
Analytics YouTube channel</a>, in the <a href="https://youtube.com/playlist?list=PLI5YfMzCfRtZ4bHJJDl_IJejxMwZFiBwz" target="_blank">Google
Analytics 4
Tutorial playlist</a>. In addition to the
videos, the code for this website and other helpful resources are available in the <a
href="https://github.com/googleanalytics" target="_blank">Google Analytics GitHub repository</a>.
videos, the code for this website and other helpful resources are available in the <a href="https://github.com/googleanalytics" target="_blank">Google Analytics GitHub repository</a>.
</p>
<p>For more information about Google Analytics, including new features and instructions,
see the Google Analytics <a href="https://support.google.com/analytics" target="_blank">help
center</a> and <a href="https://developers.google.com/analytics/devguides/collection/ga4"
target="_blank">developer site</a>.</p>
center</a> and <a href="https://developers.google.com/analytics/devguides/collection/ga4" target="_blank">developer site</a>.</p>
</div>
</main>

<%~ includeFile("footer.eta") %>

<%~ include("./partials/footer.eta") %>
11 changes: 4 additions & 7 deletions src/public/index.eta
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
<% layout("layout", { title: "Home | Google Analytics Tutorials" }) %>
<% layout("./layouts/layout", { title: "Home | Google Analytics Tutorials" }) %>

<%~ includeFile("nav") %>
<%~ include("./partials/nav") %>

<main class="container-lg pt-3 pb-5">
<h1 class="pt-4 pb-2">Hello Analytics!</h1>
<a class="twitter-share-button" target="_blank"
href="https://twitter.com/intent/tweet?text=%23HelloAnalytics%20%23GA4TutorialSeries">
<a class="twitter-share-button" target="_blank" href="https://twitter.com/intent/tweet?text=%23HelloAnalytics%20%23GA4TutorialSeries">
<span>Tweet</span></a>
<div class="pt-4 content-width">
<p>Welcome to the Google Analytics 4 Tutorial series!</p>
Expand All @@ -20,6 +19,4 @@
</div>
</main>

<%~ includeFile("footer") %>


<%~ include("./partials/footer") %>
58 changes: 34 additions & 24 deletions src/public/layouts/layout.eta
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="images/favicon.png">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

if(localStorage.getItem('consentMode') === null){

function gtag() {
dataLayer.push(arguments);
}

if (localStorage.getItem('consentMode') === null) {
gtag('consent', 'default', {
'ad_storage': 'denied',
'analytics_storage': 'denied',
Expand All @@ -25,37 +27,45 @@
gtag('consent', 'default', JSON.parse(localStorage.getItem('consentMode')));
}

if(localStorage.getItem('userId') != null) {
window.dataLayer.push({'user_id': localStorage.getItem('userId')});
if (localStorage.getItem('userId') != null) {
window.dataLayer.push({
'user_id': localStorage.getItem('userId')
});
}
</script>
<!-- Google Tag Manager -->
<script>(function (w, d, s, l, i) {
w[l] = w[l] || []; w[l].push({
'gtm.start':
new Date().getTime(), event: 'gtm.js'
}); var f = d.getElementsByTagName(s)[0],
j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src =
'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-MHJNBK6');</script>
<script>
(function(w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != 'dataLayer' ? '&l=' + l : '';
j.async = true;
j.src =
'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-MHJNBK6');
</script>
<!-- End Google Tag Manager -->
<title><%= it.title %></title>
</head>

<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MHJNBK6" height="0" width="0"
style="display:none;visibility:hidden"></iframe></noscript>
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MHJNBK6" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

<%~ it.body %>

<%~ includeFile("debug") %>
<%~ include("../partials/debug") %>

<%~ includeFile("consent") %>
<%~ include("../partials/consent") %>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>

</html>
18 changes: 7 additions & 11 deletions src/public/login.eta
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
<% layout("layout", { title: "Login - GA Tutorials" }) %>
<%~ includeFile("nav") %>
<% layout("./layouts/layout", { title: "Login - GA Tutorials" }) %>

<%~ include("./partials/nav") %>

<main class="container-lg pt-3">
<h1>Simulate login to set User ID</h1>
<form id="login-form">
<div class="form-group">
<label for="user-id">GA4 User ID</label>
<input type="text" class="form-control" id="user" name="user-id" aria-describedby="userIdHelp"
placeholder="Enter User ID">
<input type="text" class="form-control" id="user" name="user-id" aria-describedby="userIdHelp" placeholder="Enter User ID">
<small id="userIdHelp" class="form-text text-muted">This form simply
sets your User ID so tagging will include it in events. To log out, submit
the form without a value.</small>
sets your User ID so tagging will include it in events. To log out, submit
the form without a value.</small>
</div>
<button type="submit" id="btn-login" class="btn btn-primary">Submit</button>
<button type="button" id="gen-id" class="btn btn-info">Generate ID</button>
Expand All @@ -20,7 +19,6 @@
</main>

<script>

document.getElementById('btn-login').addEventListener('click', function() {
loginUserId(document.getElementById('user').value);
});
Expand Down Expand Up @@ -76,8 +74,6 @@
}

window.onload = () => document.getElementById('user').value = localStorage.getItem('userId');

</script>

<%~ includeFile("footer.eta") %>

<%~ include("./partials/footer.eta") %>
Loading

0 comments on commit d766dd4

Please sign in to comment.