-
Notifications
You must be signed in to change notification settings - Fork 1
Page Caching
The pageHandler function in the router.go file is responsible for rendering pages efficiently by leveraging a caching mechanism. This document provides an overview of how the cache works and instructions for bypassing it.
The cache is initialized with a default expiration time of 5 minutes (pageCacheDuration) and a cleanup interval of 10 minutes:
var (
pageCacheDuration = time.Minute * 5
pageCache = NewCache[string, templ.Component](pageCacheDuration, 10*time.Minute)
)When a page request is received, the function first checks if the page’s HTML is already cached:
cacheKey := path
if html, found := pageCache.Get(cacheKey); found {
c.Response().Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", pageCacheDuration/time.Second))
return cc.RenderComponent(http.StatusOK, html)
}If a cached version is found, it is returned immediately to avoid redundant computations.
If the page is not found in the cache, it is generated dynamically by:
- Fetching necessary data from the database (e.g., settings, page details, ancestors, and children).
- Rendering the page using the fetched data.
- Storing the rendered page’s HTML in the cache for future use:
pageCache.Set(cacheKey, html, pageCacheDuration)Pages marked with NoCache in the database bypass the cache and are served with HTTP headers to prevent caching:
if page.Page.NoCache {
c.Response().Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
c.Response().Header().Set("Pragma", "no-cache")
c.Response().Header().Set("Expires", "0")
}You can bypass the cache and force a fresh rendering of the page by sending a Cache-Control: no-cache header in the request. When this header is detected, the cached entry for the page is deleted:
if strings.Contains(c.Request().Header.Get("Cache-Control"), "no-cache") {
pageCache.Delete(cacheKey)
}Use the following curl command to bypass the cache for a specific page:
curl -H "Cache-Control: no-cache" http://example.com/some-pageAlternatively use chrome dev tools to disable caching. This ensures that the page is re-fetched and re-rendered without using the cached version.