Skip to content

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:

Getting Started

1. First install a library to parse the user agent.

go get github.com/mileusna/useragent

2. Update your page struct to hold the user agent

type Page struct {
	...
	UserAgent useragent.UserAgent
}

3. Parse the user agent in the pages router.go

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>
}

Clone this wiki locally