Skip to content

Commit

Permalink
Merge pull request #825 from factly/fix/api/cache
Browse files Browse the repository at this point in the history
fix cache issue
  • Loading branch information
shreeharsha-factly authored Dec 13, 2022
2 parents a856936 + ab04bfc commit b7f7e10
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 7 deletions.
7 changes: 3 additions & 4 deletions api/util/cache/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strings"

Expand All @@ -24,8 +23,9 @@ type requestBody struct {
func CachingMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(" CachingMiddleware entry")

body := requestBody{}
spaceId := r.Header.Get("x-space")
bodyBytes, _ := ioutil.ReadAll(r.Body)
err := json.Unmarshal(bodyBytes, &body)
if err != nil {
Expand All @@ -50,7 +50,7 @@ func CachingMiddleware() func(http.Handler) http.Handler {

// hash query
h := md5.New()
_, _ = io.WriteString(h, fmt.Sprint(queryStr, varString))
io.WriteString(h, fmt.Sprint(queryStr, varString, spaceId))
hash := hex.EncodeToString(h.Sum(nil))

respBodyBytes, err := GlobalCache.Get(r.Context(), hash)
Expand All @@ -64,7 +64,6 @@ func CachingMiddleware() func(http.Handler) http.Handler {
r.Body.Close()
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

log.Println(" CachingMiddleware exit")
next.ServeHTTP(w, r)
})
}
Expand Down
5 changes: 2 additions & 3 deletions api/util/cache/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ func (myrw *CacheResponseWriter) WriteHeader(header int) {

func RespMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(" RespMiddleware entry")
// Create a response writer:
crw := &CacheResponseWriter{
ResponseWriter: w,
Expand All @@ -36,6 +35,7 @@ func RespMiddleware(next http.Handler) http.Handler {

body := requestBody{}
bodyBytes, _ := ioutil.ReadAll(r.Body)
spaceId := r.Header.Get("x-space")
err := json.Unmarshal(bodyBytes, &body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Expand All @@ -58,7 +58,7 @@ func RespMiddleware(next http.Handler) http.Handler {

_ = json.Unmarshal(saveBytes, &data)

err = SaveToCache(r.Context(), fmt.Sprint(queryStr, varString), data)
err = SaveToCache(r.Context(), fmt.Sprint(queryStr, varString, spaceId), data)
if err != nil {
log.Println(err.Error())
}
Expand All @@ -67,6 +67,5 @@ func RespMiddleware(next http.Handler) http.Handler {
log.Printf("Failed to send out response: %v", err)
}

log.Println(" RespMiddleware exit")
})
}

0 comments on commit b7f7e10

Please sign in to comment.