Content: Sitemap
XML sitemaps for Hearth routes.
A sitemap lists URLs for crawlers to discover. Enable the sitemap feature and return a Sitemap from a route to serve an XML sitemap.
Serving a sitemap
This example serves a sitemap at /sitemap.xml. The relative path ./sitemap.xml adds the filename below the enclosing module. Add one entry with url or an iterator of entries with urls. Each entry can be a path string or a SitemapUrl with optional metadata.
// src/app.rs
use hearth::{
Result,
router::{
content::sitemap::{ChangeFrequency, Sitemap, SitemapUrl},
route,
},
};
#[route(GET "./sitemap.xml")]
async fn sitemap() -> Result<Sitemap> {
let posts = ["first-post", "second-post"];
Ok(Sitemap::new()
.url("/")
.url(SitemapUrl::new("/about").change_frequency(ChangeFrequency::Monthly))
.urls(posts.map(|slug| format!("/posts/{slug}"))))
}
The sitemap format requires absolute URLs, so register the base URL the application is publicly reachable at on the router. An entry given as a root-relative path is resolved against it when the response is rendered; an entry that is already an absolute http or https URL is used as is. Rendering a relative entry without a registered base URL panics.
use hearth::router::module_router;
let router = module_router!().base_url("https://example.com").build();
Entry fields
Beyond its location, a SitemapUrl carries the optional metadata of the sitemap format. Every builder method replaces the field it sets.
last_modifiedrecords when the page last changed. It accepts a value convertible intoSystemTime.change_frequencyhints how often crawlers should revisit the page, fromAlwaysfor a page that changes on every access toNeverfor an archived one.priorityranks the page relative to the other pages of the site, from0.0to1.0; crawlers treat an entry without a priority as0.5.
use std::time::SystemTime;
use hearth::router::content::sitemap::{ChangeFrequency, SitemapUrl};
let url = SitemapUrl::new("/posts/42")
.last_modified(SystemTime::now())
.change_frequency(ChangeFrequency::Weekly)
.priority(0.8);