feat: Add json presentation support; Add specifying format support

This commit is contained in:
Myzel394 2025-03-06 14:35:59 +01:00
parent 0e1c34d34e
commit 021b941199
No known key found for this signature in database
GPG Key ID: 3B955307C2FC2F11
8 changed files with 51 additions and 12 deletions

BIN
bun.lockb

Binary file not shown.

View File

@ -1,6 +1,6 @@
import { createMiddleware } from "hono/factory";
export type PresentationType = "terminal" | "browser" | "cli-browser";
export type PresentationType = "terminal" | "browser" | "cli-browser" | "json";
const TERMINAL_USER_AGENT =
/^(curl|wget|python-urllib|pycurl|java|go-http-client|php)/i;
@ -12,16 +12,53 @@ const presentation = createMiddleware<{
presentation: PresentationType;
};
}>(async (context, next) => {
const userAgent = context.req.header("User-Agent") || "";
let presentation: PresentationType = "browser";
const suggestedFormat =
context.req.query("format") || context.req.query("f");
if (TERMINAL_USER_AGENT.test(userAgent)) {
context.set("presentation", "terminal");
} else if (CLI_BROWSER_USER_AGENT.test(userAgent)) {
context.set("presentation", "cli-browser");
} else {
context.set("presentation", "browser");
switch (suggestedFormat) {
case "terminal":
case "cli":
case "script":
case "shell":
case "sh":
case "bash":
presentation = "terminal";
break;
case "browser":
case "default":
case "html":
case "web":
presentation = "browser";
break;
case "cli-browser":
case "lynx":
case "elinks":
case "w3m":
presentation = "cli-browser";
break;
case "json":
presentation = "json";
break;
default:
// Detect using User-Agent
const userAgent = context.req.header("User-Agent") || "";
if (TERMINAL_USER_AGENT.test(userAgent)) {
presentation = "terminal";
} else if (CLI_BROWSER_USER_AGENT.test(userAgent)) {
presentation = "cli-browser";
} else {
presentation = "browser";
}
}
context.set("presentation", presentation);
await next();
});

View File

@ -8,6 +8,7 @@ const realIP = createMiddleware<{
}>(async (context, next) => {
const ip =
context.req.header("x-forwarded-for") ||
context.req.header("x-real-ip") ||
getConnInfo(context).remote.address;
if (!ip) {

View File

@ -12,6 +12,7 @@ export default async function render(
browser: ".html",
terminal: ".txt",
"cli-browser": ".cli.html",
json: ".jsonn",
}[presentation];
const key = templateName + ".njk" + extension;
@ -24,5 +25,7 @@ export default async function render(
return context.html(content);
case "terminal":
return context.text(content.trimEnd());
case "json":
return context.json(JSON.parse(content));
}
}

View File

@ -0,0 +1 @@
{ "ipv4": "{{ip}}" }

View File

@ -1,6 +1,4 @@
{% extends "base.njk.cli.html" %} {% block main %}
<h2>Am I Open</h2>
<i>{{ ip }}</i>
{% if isOpen %}

View File

@ -72,8 +72,6 @@
}
</style>
{% endblock %} {% block main %}
<h2>Am I Open</h2>
<i>{{ ip }}</i>
{% if isOpen %}

1
templates/port.njk.jsonn Normal file
View File

@ -0,0 +1 @@
{"isOpen":{% if isOpen %}true{% else %}false{% endif %}}