Skip to main content

Cache Tags using Workers

还没翻译译自英文(developers.cloudflare.com)本页 8 段都还没译

If you want to get started quickly, click on the button below.

Deploy to Cloudflare

This creates a repository in your GitHub account and deploys the application to Cloudflare Workers.

JavaScriptTypeScriptHonoPython

export default {
	async fetch(request) {
		const requestUrl = new URL(request.url);
		const params = requestUrl.searchParams;
		const tags =
			params && params.has("tags") ? params.get("tags").split(",") : [];
		const url = params && params.has("uri") ? params.get("uri") : "";
		if (!url) {
			const errorObject = {
				error: "URL cannot be empty",
			};
			return new Response(JSON.stringify(errorObject), { status: 400 });
		}
		const init = {
			cf: {
				cacheTags: tags,
			},
		};
		return fetch(url, init)
			.then((result) => {
				const cacheStatus = result.headers.get("cf-cache-status");
				const lastModified = result.headers.get("last-modified");
				const response = {
					cache: cacheStatus,
					lastModified: lastModified,
				};
				return new Response(JSON.stringify(response), {
					status: result.status,
				});
			})
			.catch((err) => {
				const errorObject = {
					error: err.message,
				};
				return new Response(JSON.stringify(errorObject), { status: 500 });
			});
	},
};