generate sitemap.xml ใน hono framework
generate sitemap.xml ใน hono framework
ในการทำเว็บ เราต้องมี sitemap.xml ไว้ เพื่อให้บอทเก็บข้อมูลเว็บไซต์เราได้ครบทุก url ดังนั้น เราไปดูวิธีการ generate sitemap.xml ใน hono framework กันครับ
ก่อนอื่นเราก็สร้า่ง get ขึ้นมา เพื่อสร้าง url ของ sitemap.xml ตามตัวอย่างโค้ดด้านล่าง
app.get('/sitemap.xml', (c: any) => {
c.header('Content-Type', 'application/xml');
return c.body(generateSitemapIndex());
})
จากโค้ด เราจะเซ็ต header Content-Type ให้เป็น application/xml เพื่อเราจะได้ return เป็น xml กลับไปคับ จากนั้นผมจะเรียกไปฟังก์ชัน generateSitemapIndex เพื่อ generate sitemap คับ
ตัวอย่าง generateSitemapIndex ตัวนี้ผมจะ generate sitemap index ขึ้นมา ตามตัวอย่าง
export const generateSitemapIndex = () => {
return `<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>https://www.doesystem.com/sitemap-cat.xml</loc>
</sitemap>
</sitemapindex>`
}
ตัวอย่างต่อไปนี้เป็นการ generate sitemap โดยผมจะ query ข้อมูลมาจาก database แล้วทำการ generate ขึ้นมาครับ ตามตัวอย่างเลย
export const generateSitemapCat = async (c: any) => {
let sitemap = `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">`
sitemap += `<url>
<loc>https://www.doesystem.com/</loc>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>`
sitemap += `<url>
<loc>https://www.doesystem.com/post</loc>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>`
try {
let queryPage: string = "SELECT menu FROM doe_category";
let stmt = c.env.DB.prepare(queryPage);
const {results} = await stmt.all()
results.map((item: any) => {
sitemap += `<url>
<loc>https://www.doesystem.com/category/${item.menu}/1.html</loc>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>`
})
} catch (e) {
console.error(e)
}
sitemap += `</urlset>`
return sitemap
}