-
Notifications
You must be signed in to change notification settings - Fork 1
User Agent
Stuart George edited this page Dec 3, 2024
·
2 revisions
This is if you want to render different content based on user agent such as mobile or desktop:
go get github.com/mileusna/useragenttype Page struct {
...
UserAgent useragent.UserAgent
}Take care to set the cacheKey based on the user agent. An example below:
func pageHandler(c echo.Context) error {
cc := c.(*middleware.CustomContext)
path := normalizePath(c.Request().URL.Path)
ua := useragent.Parse(c.Request().UserAgent())
cacheKey := buildCacheKey(ua, path)
...
pageComponent := &pages.Page{
...
UserAgent: ua,
}
...
}
func buildCacheKey(ua useragent.UserAgent, path string) string {
device := "desktop"
if ua.Mobile {
device = "mobile"
} else if ua.Tablet {
device = "tablet"
}
return fmt.Sprintf("%s:%s", device, path)
}You can then use the user agent in the templ components that ref the Page such as:
if page.UserAgent.Mobile {
<div>mobile</div>
} else {
<div>desktop or tablet</div>
}