Skip to content

Remove trailing spaces #21764

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Remove trailing spaces
  • Loading branch information
vil02 committed Apr 16, 2025
commit 80c0441ce8155bbe533da1e3b57f1cadcb062da7
12 changes: 6 additions & 6 deletions src/content/docs/workers/examples/alter-headers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ async def on_fetch(request):

# Add a custom header with a value
new_headers["x-workers-hello"] = "Hello from Cloudflare Workers"

# Delete headers
if "x-header-to-delete" in new_headers:
del new_headers["x-header-to-delete"]
Expand All @@ -113,27 +113,27 @@ const app = new Hono();
app.use('*', async (c, next) => {
// Process the request with the next middleware/handler
await next();

// After the response is generated, we can modify its headers

// Add a custom header with a value
c.res.headers.append(
"x-workers-hello",
"Hello from Cloudflare Workers with Hono"
);

// Delete headers
c.res.headers.delete("x-header-to-delete");
c.res.headers.delete("x-header2-to-delete");

// Adjust the value for an existing header
c.res.headers.set("x-header-to-change", "NewValue");
});

app.get('*', async (c) => {
// Fetch content from example.com
const response = await fetch("https://example.com");

// Return the response body with original headers
// (our middleware will modify the headers before sending)
return new Response(response.body, {
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/workers/examples/auth-with-headers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ app.use('*', async (c, next) => {
*/
const PRESHARED_AUTH_HEADER_KEY = "X-Custom-PSK";
const PRESHARED_AUTH_HEADER_VALUE = "mypresharedkey";

// Get the pre-shared key from the request header
const psk = c.req.header(PRESHARED_AUTH_HEADER_KEY);

Expand Down
16 changes: 8 additions & 8 deletions src/content/docs/workers/examples/cache-using-fetch.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ const app = new Hono<{ Bindings: Bindings }>();

app.all('*', async (c) => {
const url = new URL(c.req.url);

// Only use the path for the cache key, removing query strings
// and always store using HTTPS, for example, https://www.example.com/file-uri-here
const someCustomKey = `https://${url.hostname}${url.pathname}`;

// Fetch the request with custom cache settings
let response = await fetch(c.req.raw, {
cf: {
Expand All @@ -103,13 +103,13 @@ app.all('*', async (c) => {
cacheKey: someCustomKey,
},
});

// Reconstruct the Response object to make its headers mutable
response = new Response(response.body, response);

// Set cache control headers to cache on browser for 25 minutes
response.headers.set("Cache-Control", "max-age=1500");

return response;
});

Expand Down Expand Up @@ -278,17 +278,17 @@ const app = new Hono<{ Bindings: Bindings }>();
app.all('*', async (c) => {
const originalUrl = c.req.url;
const url = new URL(originalUrl);

// Randomly select a storage backend
if (Math.random() < 0.5) {
url.hostname = "example.s3.amazonaws.com";
} else {
url.hostname = "example.storage.googleapis.com";
}

// Create a new request to the selected backend
const newRequest = new Request(url, c.req.raw);

// Fetch using the original URL as the cache key
return fetch(newRequest, {
cf: { cacheKey: originalUrl },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ app.get('*', async (c) => {

// Cast the raw request to include Cloudflare-specific properties
const request = c.req.raw as RequestWithCf;

// Use the cf object to obtain the country of the request
// more on the cf object: https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
const country = request.cf.country;
Expand Down
4 changes: 2 additions & 2 deletions src/content/docs/workers/examples/cron-trigger.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@ app.get('/', (c) => c.text('Hello World!'));
export default {
// The Hono app handles regular HTTP requests
fetch: app.fetch,

// The scheduled function handles Cron triggers
async scheduled(
controller: ScheduledController,
env: Env,
ctx: ExecutionContext,
) {
console.log("cron processed");

// You could also perform actions like:
// - Fetching data from external APIs
// - Updating KV or Durable Object storage
Expand Down
14 changes: 7 additions & 7 deletions src/content/docs/workers/examples/data-loss-prevention.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -258,30 +258,30 @@ async function postDataBreach(request: Request) {
app.use('*', async (c) => {
// Fetch the origin response
const response = await fetch(c.req.raw);

// Return origin response if response wasn't text
const contentType = response.headers.get("content-type") || "";
if (!contentType.toLowerCase().includes("text/")) {
return response;
}

// Get the response text
let text = await response.text();

// When debugging, replace the response from the origin with an email
text = DEBUG
? text.replace("You may use this", "[email protected] may use this")
: text;

// Check for sensitive data
for (const kind in sensitiveRegexsMap) {
const sensitiveRegex = new RegExp(sensitiveRegexsMap[kind], "ig");
const match = sensitiveRegex.test(text);

if (match) {
// Alert a data breach
await postDataBreach(c.req.raw);

// Respond with a block if credit card, otherwise replace sensitive text with `*`s
if (kind === "creditCard") {
return c.text(`${kind} found\nForbidden\n`, 403);
Expand All @@ -294,7 +294,7 @@ app.use('*', async (c) => {
}
}
}

// Return the modified response
return new Response(text, {
status: response.status,
Expand Down
16 changes: 8 additions & 8 deletions src/content/docs/workers/examples/debugging-logs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ app.use('*', async (c, next) => {
try {
// Process the request with the next handler
await next();

// After processing, check if the response indicates an error
if (c.res && (!c.res.ok && !c.res.redirected)) {
const body = await c.res.clone().text();
Expand All @@ -180,28 +180,28 @@ app.use('*', async (c, next) => {
body.trim().substring(0, 10)
);
}

} catch (err) {
// Without waitUntil, the fetch to the logging service may not complete
c.executionCtx.waitUntil(
postLog(err.toString())
);

// Get the error stack or error itself
const stack = JSON.stringify(err.stack) || err.toString();

// Create a new response with the error information
const response = c.res ?
const response = c.res ?
new Response(stack, {
status: c.res.status,
headers: c.res.headers
}) :
}) :
new Response(stack, { status: 500 });

// Add debug headers
response.headers.set("X-Debug-stack", stack);
response.headers.set("X-Debug-err", err.toString());

// Set the modified response
c.res = response;
}
Expand Down
6 changes: 3 additions & 3 deletions src/content/docs/workers/examples/extract-cookie-value.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,15 @@ const app = new Hono();
app.get('*', (c) => {
// The name of the cookie
const COOKIE_NAME = "__uid";

// Get the specific cookie value using Hono's cookie helper
const cookieValue = getCookie(c, COOKIE_NAME);

if (cookieValue) {
// Respond with the cookie value
return c.text(cookieValue);
}

return c.text("No cookie with name: " + COOKIE_NAME);
});

Expand Down
4 changes: 2 additions & 2 deletions src/content/docs/workers/examples/fetch-json.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ app.get('*', async (c) => {
async function gatherResponse(response: Response) {
const { headers } = response;
const contentType = headers.get("content-type") || "";

if (contentType.includes("application/json")) {
return { contentType, result: JSON.stringify(await response.json()) };
}

return { contentType, result: await response.text() };
}

Expand Down
14 changes: 7 additions & 7 deletions src/content/docs/workers/examples/geolocation-app-weather.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -149,18 +149,18 @@ app.get('*', async (c) => {
// Get API endpoint
let endpoint = "https://api.waqi.info/feed/geo:";
const token = ""; // Use a token from https://aqicn.org/api/

// Define styles
const html_style = `body{padding:6em; font-family: sans-serif;} h1{color:#f6821f}`;

// Get geolocation from Cloudflare request
const req = c.req.raw;
const latitude = req.cf?.latitude;
const longitude = req.cf?.longitude;

// Create complete API endpoint with coordinates
endpoint += `${latitude};${longitude}/?token=${token}`;

// Fetch weather data
const init = {
headers: {
Expand All @@ -169,7 +169,7 @@ app.get('*', async (c) => {
};
const response = await fetch(endpoint, init);
const content = await response.json() as WeatherApiResponse;

// Build HTML content
const weatherContent = html`
<h1>Weather 🌦</h1>
Expand All @@ -181,7 +181,7 @@ app.get('*', async (c) => {
<p>The O3 level is: ${content.data.iaqi.o3?.v}.</p>
<p>The temperature is: ${content.data.iaqi.t?.v}°C.</p>
`;

// Complete HTML document
const htmlDocument = html`
<!DOCTYPE html>
Expand All @@ -195,7 +195,7 @@ app.get('*', async (c) => {
</div>
</body>
`;

// Return HTML response
return c.html(htmlDocument);
});
Expand Down
20 changes: 10 additions & 10 deletions src/content/docs/workers/examples/geolocation-custom-styling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -485,19 +485,19 @@ async function toCSSGradient(hour: number): Promise<string> {
let css = "linear-gradient(to bottom,";
const data = grads[hour];
const len = data.length;

for (let i = 0; i < len; i++) {
const item = data[i];
css += ` #${item.color} ${item.position}%`;
if (i < len - 1) css += ",";
}

return css + ")";
}

app.get('*', async (c) => {
const request = c.req.raw;

// Base HTML style
let html_style = `
html{width:100vw; height:100vh;}
Expand All @@ -511,26 +511,26 @@ app.get('*', async (c) => {
color:white;
font-family:sans-serif;
}`;

// Get timezone from Cloudflare request
const timezone = request.cf?.timezone || 'UTC';
console.log(timezone);

// Get localized time
let localized_date = new Date(
new Date().toLocaleString("en-US", { timeZone: timezone })
);

let hour = localized_date.getHours();
let minutes = localized_date.getMinutes();

// Generate HTML content
let html_content = `<h1>${hour}:${minutes}</h1>`;
html_content += `<p>${timezone}<br/></p>`;

// Add background gradient based on hour
html_style += `body{background:${await toCSSGradient(hour)};}`;

// Complete HTML document
let html = `
<!DOCTYPE html>
Expand All @@ -543,7 +543,7 @@ app.get('*', async (c) => {
${html_content}
</div>
</body>`;

return c.html(html);
});

Expand Down
6 changes: 3 additions & 3 deletions src/content/docs/workers/examples/images-workers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,12 @@ app.get('*', async (c) => {
// You can find this in the dashboard, it should look something like this: ZWd9g1K7eljCn_KDTu_MWA
// Either get it from environment or hardcode it here
const accountHash = c.env.ACCOUNT_HASH || "";

const url = new URL(c.req.url);

// A request to something like cdn.example.com/83eb7b2-5392-4565-b69e-aff66acddd00/public
// will fetch "https://imagedelivery.net/<accountHash>/83eb7b2-5392-4565-b69e-aff66acddd00/public"

return fetch(`https://imagedelivery.net/${accountHash}${url.pathname}`);
});

Expand Down
Loading