fix #1 Cart is empty
Some checks failed
Build / test (push) Failing after 2m50s

This commit is contained in:
2025-04-13 16:07:53 +02:00
parent fa561c921d
commit 8a7d66f815

View File

@@ -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)
}