You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm writing some middleware to do simple cache responses. Specifically, it will return an HTTP 304, and will return no body and no content-type header if the if-none-match or if-modified-since request headers match the corresponding etag or last-modified response headers.
All of this is easy enough, except changing the response body. Specifically, what I've got is this:
func cachingMiddleware() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { ifNoneMatch := c.Request().Header.Get("if-none-match") ifModifiedSince := c.Request().Header.Get("if-modified-since") c.Response().Before(func() { etag := c.Response().Header().Get("etag") lastModified := c.Response().Header().Get("last-modified") cacheHit := true switch { case ifNoneMatch == "" && ifModifiedSince == "": // No cache headers! cacheHit = false case ifNoneMatch != "" && ifNoneMatch != etag: // If-None-Match header provided and differs from ETag. cacheHit = false case ifModifiedSince != "" && ifModifiedSince != lastModified: // If-Modified-Since header provided and differs from Last-Modified. cacheHit = false } slog.Debug("Caching result", "if-none-match", ifNoneMatch, "if-modified-since", ifModifiedSince, "etag", etag, "last-modified", lastModified, "cacheHit", cacheHit, ) if cacheHit { c.Response().Status = http.StatusNotModified c.Response().Header().Del("content-type") // TODO: DON'T SEND THE RESPONSE BODY } }) result := next(c) return result } } }
The bit that I can't work out is the "TODO: DON'T SEND THE RESPONSE BODY" bit.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
I'm writing some middleware to do simple cache responses. Specifically, it will return an HTTP 304, and will return no body and no
content-typeheader if theif-none-matchorif-modified-sincerequest headers match the correspondingetagorlast-modifiedresponse headers.All of this is easy enough, except changing the response body. Specifically, what I've got is this:
The bit that I can't work out is the "TODO: DON'T SEND THE RESPONSE BODY" bit.
What's the recommended way to achieve this?
Cheers
Beta Was this translation helpful? Give feedback.
All reactions