Menu

ETag-Based Caching for Dynamic Pages in Go
📰

ETag-Based Caching for Dynamic Pages in Go

DEV Community: go·Anton Makasin·5 days ago
#EYCeLePF
#devtogo#devto#dev#cache#body
Reading 0:00
15s threshold

Many of our cacheable HTML GET responses include an ETag. When a browser revalidates a cached page and the representation has not changed, we return 304 Not Modified : no response body, less transfer, and no need to compress that body again.

How It Works

We render the full HTML into a buffer, hash it with xxhash, and compare against the client's If-None-Match header:

func WriteHTMLWithETag ( c * gin . Context , body [] byte ) { c . Header ( "Content-Type" , "text/html; charset=utf-8" )

etag := ContentETag ( body )

c . Header ( "Vary" , "Accept, HX-Request, X-Catalog-More" ) c . Header ( "ETag" , etag ) c . Header ( "Cache-Control" , "private, no-cache, must-revalidate" )

if ETagMatches ( c . GetHeader ( "If-None-Match" ), etag ) { c . Status ( http . StatusNotModified ) return }

c . Status ( http . StatusOK ) c . Writer . Write ( body ) }

Enter fullscreen mode

Exit fullscreen mode

private prevents shared caches from storing the response.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.