Skip to content

Commit

Permalink
fix: Improve
Browse files Browse the repository at this point in the history
  • Loading branch information
dadav committed Dec 25, 2024
1 parent 9a86d8f commit a568f34
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
8 changes: 5 additions & 3 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,6 @@ You can also enable the caching functionality to speed things up.`,

r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

shouldCache := false
for _, prefix := range cachePrefixes {
if strings.HasPrefix(r.URL.Path, strings.TrimSpace(prefix)) {
Expand All @@ -168,13 +167,16 @@ You can also enable the caching functionality to speed things up.`,

if shouldCache {
log.Log.Debugf("Caching request for path: %s", r.URL.Path)
cachedMiddleware(next).ServeHTTP(w, r)
wrapper := customMiddleware.NewResponseWrapper(w)
cachedMiddleware(next).ServeHTTP(wrapper, r)
if wrapper.WasWritten() {
w.Header().Set("X-Cache", "HIT")
}
} else {
next.ServeHTTP(w, r)
}
})
})

}

if config.UI {
Expand Down
26 changes: 26 additions & 0 deletions internal/middleware/response_wrapper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package middleware

import "net/http"

type ResponseWrapper struct {
http.ResponseWriter
written bool
}

func NewResponseWrapper(w http.ResponseWriter) *ResponseWrapper {
return &ResponseWrapper{ResponseWriter: w}
}

func (w *ResponseWrapper) Write(b []byte) (int, error) {
w.written = true
return w.ResponseWriter.Write(b)
}

func (w *ResponseWrapper) WriteHeader(statusCode int) {
w.written = true
w.ResponseWriter.WriteHeader(statusCode)
}

func (w *ResponseWrapper) WasWritten() bool {
return w.written
}

0 comments on commit a568f34

Please sign in to comment.