Skip to content

Commit

Permalink
feat:remove duplicate headers from rw
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamed-abdelrhman committed Apr 22, 2024
1 parent b5b7462 commit f6a2c60
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
19 changes: 10 additions & 9 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,33 +90,34 @@ func (c *Cache) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}

// Cache miss - record the response
recorder := &responseRecorder{rw: rw}
recorder := &responseRecorder{
rw: rw,
header: rw.Header().Clone(), // Initialize with the original headers.
}
c.next.ServeHTTP(recorder, req)

// Serialize the response data
cachedResponse := CachedResponse{
StatusCode: recorder.status,
Headers: recorder.Header().Clone(), // Convert http.Header to a map for serialization
Headers: recorder.Header(), // Convert http.Header to a map for serialization
Body: recorder.body.Bytes(),
}
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
if err := enc.Encode(cachedResponse); err != nil {
log.Printf("Failed to serialize response for caching: %s", err)
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
} else {
// Store the serialized response in Redis
if err := respClient.SetWithTTL(req.Context(), cacheKey, buffer.String(), c.cacheExpiry); err != nil {
log.Printf("Failed to cache response in Redis: %s", err.Error())
}
}

// Write the response to the client
for key, values := range recorder.Header() {
for _, value := range values {
rw.Header().Add(key, value)
}
if _, err := rw.Write(recorder.body.Bytes()); err != nil {
log.Printf("Failed to write response body: %s", err)
return
}
rw.WriteHeader(recorder.status)
rw.Write(recorder.body.Bytes())
return
}
8 changes: 4 additions & 4 deletions recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@ type responseRecorder struct {
rw http.ResponseWriter
status int
body bytes.Buffer
header http.Header
}

func (r *responseRecorder) Header() http.Header {
return r.rw.Header()
return r.header
}

func (r *responseRecorder) Write(b []byte) (int, error) {
r.body.Write(b)
return r.rw.Write(b)
return r.body.Write(b) // Just buffer the body, don't write to rw

}

func (r *responseRecorder) WriteHeader(statusCode int) {
r.status = statusCode
r.rw.WriteHeader(statusCode)
}

0 comments on commit f6a2c60

Please sign in to comment.