第14章 Sitemap 站点地图生成指南
Sitemap:Iris 对 Sitemap 协议提供了广泛支持,并自动生成 sitemap 索引“/sitemap.xml”。要在 Web 应用中启用 sitemap,需使用 iris.WithSitemap Configurator。该函数接受已暴露应用的完整协议和域名:
```go app := iris.New() // [...] app.Listen(":8080", iris.WithSitemap("http://localhost:8080")) ```
应用会遍历已注册的静态路由,并将每个路由添加到 sitemap 文件中。默认情况下,仅填充 `
```go app.Get("/home", handler).SetLastMod(time.Now()).SetChangeFreq("hourly").SetPriority(0.8) ```
静态路由通过 GET 方法暴露,且其路径不包含动态参数。例如 /home、/about,但不包括 /user/{id:uint64} 等。
示例代码:
```go package main
import ( "time"
"github.com/kataras/iris/v12" )
const startURL = "http://localhost:8080"
func main() { app := newApp()
// http://localhost:8080/sitemap.xml // 仅列出在线的 GET 静态路由。 // // 参考: https://www.sitemaps.org/protocol.html app.Listen(":8080", iris.WithSitemap(startURL)) }
func newApp() *iris.Application { app := iris.New() app.Logger().SetLevel("debug")
lastModified, _ := time.Parse("2006-01-02T15:04:05-07:00", "2019-12-13T21:50:33+02:00") app.Get("/home", handler).SetLastMod(lastModified).SetChangeFreq("hourly").SetPriority(1) app.Get("/articles", handler).SetChangeFreq("daily") app.Get("/path1", handler) app.Get("/path2", handler)
app.Post("/this-should-not-be-listed", handler) app.Get("/this/{myparam}/should/not/be/listed", handler) app.Get("/this-should-not-be-listed-offline", handler).SetStatusOffline()
// 这些也应当被排除 app.Get("/about", handler).ExcludeSitemap() app.Get("/offline", handler).SetStatusOffline()
return app }
func handler(ctx iris.Context) { ctx.WriteString(ctx.Path()) } ```
多语言(Localization)
Sitemap 会自动为每个路由生成多语言翻译链接:当 app.I18n.PathRedirect 为 true 时按路径前缀生成,当 app.I18n.Subdomain 为 true 时按子域名生成,或当 app.I18n.URLParameter 不为空时按 URL 查询参数生成。
详情参见:https://support.google.com/webmasters/answer/189077?hl=ensh
请求示例:
GET http://localhost:8080/sitemap.xml
返回结果: