diff --git a/controllers/cartItemController.go b/controllers/cartItemController.go index 2f6eadf..2f305ef 100644 --- a/controllers/cartItemController.go +++ b/controllers/cartItemController.go @@ -7,6 +7,7 @@ import ( "fmt" "net/http" "strconv" + "strings" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -36,6 +37,22 @@ func NewCartItemController() CartItemController { return &cartItemController{} } +// getSetCookieValue retrieves the value of a cookie from the Set-Cookie header +func getSetCookieValue(c *gin.Context, cookieName string) string { + // Check the Set-Cookie headers + cookies := c.Writer.Header()["Set-Cookie"] + for _, cookie := range cookies { + if strings.HasPrefix(cookie, cookieName+"=") { + // Extract the cookie value + parts := strings.SplitN(cookie, ";", 2) + if len(parts) > 0 { + return strings.TrimPrefix(parts[0], cookieName+"=") + } + } + } + return "" // Return empty string if cookie is not found +} + func generateSessionId(length int) string { bytes := make([]byte, length) // 16 bytes = 128 bits _, err := rand.Read(bytes) @@ -49,6 +66,13 @@ func GetSessionId(ctx *gin.Context) string { sessionId, err := ctx.Cookie("session_id") if err != nil { + //we need to check if we already set cookie in the response so that we dont do this multiple times + responseCookie := getSetCookieValue(ctx, "session_id") + + if len(responseCookie) != 0 { + return responseCookie + } + sessionId = generateSessionId(16) ctx.SetCookie("session_id", sessionId, 3600, "/", "", false, true) }