提交正式官网
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import { send } from 'h3'
|
||||
import { sitemapRoutes } from '~/data/sitemap-routes'
|
||||
import { getSiteUrlFromEvent } from '~/server/utils/site-url'
|
||||
import { toLocalePath } from '~/utils/locale-path'
|
||||
import { toAbsoluteUrl } from '~/utils/seo'
|
||||
import type { SiteLocale } from '~/types/locale'
|
||||
|
||||
function escapeXml(value: string): string {
|
||||
return value
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''')
|
||||
}
|
||||
|
||||
function buildAlternateLinks(siteUrl: string, basePath: string): string {
|
||||
const enUrl = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, 'en')))
|
||||
const zhUrl = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(basePath, 'zh')))
|
||||
|
||||
return [
|
||||
` <xhtml:link rel="alternate" hreflang="en" href="${enUrl}" />`,
|
||||
` <xhtml:link rel="alternate" hreflang="zh-CN" href="${zhUrl}" />`,
|
||||
` <xhtml:link rel="alternate" hreflang="x-default" href="${enUrl}" />`
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export default defineEventHandler((event) => {
|
||||
const config = useRuntimeConfig()
|
||||
const siteUrl = getSiteUrlFromEvent(event, String(config.public.siteUrl))
|
||||
const lastmod = new Date().toISOString().slice(0, 10)
|
||||
const locales: SiteLocale[] = ['en', 'zh']
|
||||
|
||||
const urls = sitemapRoutes
|
||||
.flatMap((route) =>
|
||||
locales.map((locale) => {
|
||||
const loc = escapeXml(toAbsoluteUrl(siteUrl, toLocalePath(route.path, locale)))
|
||||
return [
|
||||
' <url>',
|
||||
` <loc>${loc}</loc>`,
|
||||
buildAlternateLinks(siteUrl, route.path),
|
||||
` <lastmod>${lastmod}</lastmod>`,
|
||||
` <changefreq>${route.changefreq}</changefreq>`,
|
||||
` <priority>${route.priority.toFixed(1)}</priority>`,
|
||||
' </url>'
|
||||
].join('\n')
|
||||
})
|
||||
)
|
||||
.join('\n')
|
||||
|
||||
const body = [
|
||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||
'<?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>',
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">',
|
||||
urls,
|
||||
'</urlset>',
|
||||
''
|
||||
].join('\n')
|
||||
|
||||
setResponseHeaders(event, {
|
||||
'content-type': 'application/xml; charset=utf-8',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'cache-control': 'public, max-age=3600'
|
||||
})
|
||||
|
||||
return send(event, body)
|
||||
})
|
||||
Reference in New Issue
Block a user