Skip to content
This repository has been archived by the owner on Oct 27, 2024. It is now read-only.

Commit

Permalink
Make changing port and hostname possible with environment variables (#11
Browse files Browse the repository at this point in the history
)

* Use to Deno.execPath

The current "new URL(import.meta.url).pathname" will not resolve to the current path if we use deno compile.

* Provide adapter option to determine the path

* Introduce environment variables to change the port and hostname

* Add documentation and change default hostname

* Do not use a dependency

* Set correct default host

* Fix default hostname
  • Loading branch information
tiloio authored Oct 24, 2024
1 parent 045c5ef commit a8e46ca
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,20 @@ deployment.

Using [deployctl](https://deno.com/deploy/docs/deployctl):

```
```sh
deployctl deploy --project=demo --import-map=import_map.json mod.ts
```

### Change the port or hostname

The following environment variables can be used to change the port and hostname:

```sh
PORT=5678 HOST=0.0.0.0 deno run --allow-env --allow-read --allow-net mod.ts
```

The default port is `8000` and the default hostname is `127.0.0.1`.

## Adapter options

See the [TypeScript definition](/index.d.ts) for `AdapterOptions`. You can
Expand Down
15 changes: 10 additions & 5 deletions files/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@ const baseDir = dirname(CURRENT_DIRNAME);
const rootDir = join(baseDir, "static");

Deno.serve(
{
port: Number.parseInt(Deno.env.get("PORT") ?? "8000"),
hostname: Deno.env.get("HOST") ?? "0.0.0.0",
},
async (request: Request, info: Deno.ServeHandlerInfo): Promise<Response> => {
// Get client IP address
const clientAddress = request.headers.get("x-forwarded-for") ??
info.remoteAddr.hostname;
const clientAddress =
request.headers.get("x-forwarded-for") ?? info.remoteAddr.hostname;

const { pathname } = new URL(request.url);

Expand All @@ -38,7 +42,7 @@ Deno.serve(
if (!slashed && !extname(pathname) && prerendered.has(pathname)) {
const response = await serveFile(
request,
join(rootDir, `${pathname}.html`),
join(rootDir, `${pathname}.html`)
);
if (response.ok || response.status === 304) {
return response;
Expand All @@ -57,16 +61,17 @@ Deno.serve(
) {
response.headers.set(
"cache-control",
"public, max-age=31536000, immutable",
"public, max-age=31536000, immutable"
);
}
return response;
}

// Pass to the SvelteKit server
await initialized;

return server.respond(request, {
getClientAddress: () => clientAddress,
});
},
}
);

0 comments on commit a8e46ca

Please sign in to comment.