From fb09c825e8e13134daaa90debfda198520e1b347 Mon Sep 17 00:00:00 2001 From: NARITA <58836324+Narita-1095305@users.noreply.github.com> Date: Wed, 21 May 2025 09:20:44 +0900 Subject: [PATCH] feat(context): add SetCookieData (#4240) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(context): add SetCookieStruct (#4215)# This is a combination of 2 commits. feat(context): add SetCookieStruct (#4215) feat(context): add SetCookieStruct (#4215) * feat(context): add SetCookieStruct (#4215) * feat(context): fix SetCookieStruct→SetCookieData (gin-gonic#4215) * fix(context): respect caller-specified SameSite value in SetCookieData --- context.go | 13 +++++ context_test.go | 126 ++++++++++++++++++++++++++++++++++++++++++++++++ docs/doc.md | 54 ++++++++++++++++++++- 3 files changed, 192 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 1c76c0f6..d3e4c6d7 100644 --- a/context.go +++ b/context.go @@ -1027,6 +1027,19 @@ func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, }) } +// SetCookieData adds a Set-Cookie header to the ResponseWriter's headers. +// It accepts a pointer to http.Cookie structure for more flexibility in setting cookie attributes. +// The provided cookie must have a valid Name. Invalid cookies may be silently dropped. +func (c *Context) SetCookieData(cookie *http.Cookie) { + if cookie.Path == "" { + cookie.Path = "/" + } + if cookie.SameSite == http.SameSiteDefaultMode { + cookie.SameSite = c.sameSite + } + http.SetCookie(c.Writer, cookie) +} + // Cookie returns the named cookie provided in the request or // ErrNoCookie if not found. And return the named cookie is unescaped. // If multiple cookies match the given name, only one cookie will diff --git a/context_test.go b/context_test.go index ef0cfccd..c2f82410 100644 --- a/context_test.go +++ b/context_test.go @@ -3123,3 +3123,129 @@ func TestContextNext(t *testing.T) { assert.True(t, exists) assert.Equal(t, "value3", value) } + +func TestContextSetCookieData(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.SetSameSite(http.SameSiteLaxMode) + var setCookie string + + // Basic cookie settings + cookie := &http.Cookie{ + Name: "user", + Value: "gin", + MaxAge: 1, + Path: "/", + Domain: "localhost", + Secure: true, + HttpOnly: true, + } + c.SetCookieData(cookie) + setCookie = c.Writer.Header().Get("Set-Cookie") + assert.Contains(t, setCookie, "user=gin") + assert.Contains(t, setCookie, "Path=/") + assert.Contains(t, setCookie, "Domain=localhost") + assert.Contains(t, setCookie, "Max-Age=1") + assert.Contains(t, setCookie, "HttpOnly") + assert.Contains(t, setCookie, "Secure") + // SameSite=Lax might be omitted in Go 1.23+ as it's the default + // assert.Contains(t, setCookie, "SameSite=Lax") + + // Test that when Path is empty, "/" is automatically set + cookie = &http.Cookie{ + Name: "user", + Value: "gin", + MaxAge: 1, + Path: "", + Domain: "localhost", + Secure: true, + HttpOnly: true, + } + c.SetCookieData(cookie) + setCookie = c.Writer.Header().Get("Set-Cookie") + assert.Contains(t, setCookie, "user=gin") + assert.Contains(t, setCookie, "Path=/") + assert.Contains(t, setCookie, "Domain=localhost") + assert.Contains(t, setCookie, "Max-Age=1") + assert.Contains(t, setCookie, "HttpOnly") + assert.Contains(t, setCookie, "Secure") + // SameSite=Lax might be omitted in Go 1.23+ as it's the default + // assert.Contains(t, setCookie, "SameSite=Lax") + + // Test additional cookie attributes (Expires) + expireTime := time.Now().Add(24 * time.Hour) + cookie = &http.Cookie{ + Name: "user", + Value: "gin", + Path: "/", + Domain: "localhost", + Expires: expireTime, + Secure: true, + HttpOnly: true, + } + c.SetCookieData(cookie) + + // Since the Expires value varies by time, partially verify with Contains + setCookie = c.Writer.Header().Get("Set-Cookie") + assert.Contains(t, setCookie, "user=gin") + assert.Contains(t, setCookie, "Path=/") + assert.Contains(t, setCookie, "Domain=localhost") + assert.Contains(t, setCookie, "HttpOnly") + assert.Contains(t, setCookie, "Secure") + // SameSite=Lax might be omitted in Go 1.23+ as it's the default + // assert.Contains(t, setCookie, "SameSite=Lax") + + // Test for Partitioned attribute (Go 1.18+) + cookie = &http.Cookie{ + Name: "user", + Value: "gin", + Path: "/", + Domain: "localhost", + Secure: true, + HttpOnly: true, + Partitioned: true, + } + c.SetCookieData(cookie) + setCookie = c.Writer.Header().Get("Set-Cookie") + assert.Contains(t, setCookie, "user=gin") + assert.Contains(t, setCookie, "Path=/") + assert.Contains(t, setCookie, "Domain=localhost") + assert.Contains(t, setCookie, "HttpOnly") + assert.Contains(t, setCookie, "Secure") + // SameSite=Lax might be omitted in Go 1.23+ as it's the default + // assert.Contains(t, setCookie, "SameSite=Lax") + // Not testing for Partitioned attribute as it may not be supported in all Go versions + + // Test that SameSiteStrictMode is explicitly included in the header + t.Run("SameSite=Strict is included", func(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + cookie := &http.Cookie{ + Name: "user", + Value: "gin", + Path: "/", + Domain: "localhost", + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteStrictMode, + } + c.SetCookieData(cookie) + setCookie := c.Writer.Header().Get("Set-Cookie") + assert.Contains(t, setCookie, "SameSite=Strict") + }) + + // Test that SameSiteNoneMode is explicitly included in the header + t.Run("SameSite=None is included", func(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + cookie := &http.Cookie{ + Name: "user", + Value: "gin", + Path: "/", + Domain: "localhost", + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteNoneMode, + } + c.SetCookieData(cookie) + setCookie := c.Writer.Header().Get("Set-Cookie") + assert.Contains(t, setCookie, "SameSite=None") + }) +} diff --git a/docs/doc.md b/docs/doc.md index 9b7b1ec9..0e882a1b 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -2304,12 +2304,64 @@ func main() { router := gin.Default() router.GET("/cookie", func(c *gin.Context) { + cookie, err := c.Cookie("gin_cookie") + if err != nil { + cookie = "NotSet" + // Using http.Cookie struct for more control + c.SetCookieData(&http.Cookie{ + Name: "gin_cookie", + Value: "test", + Path: "/", + Domain: "localhost", + MaxAge: 3600, + Secure: false, + HttpOnly: true, + // Additional fields available in http.Cookie + Expires: time.Now().Add(24 * time.Hour), + // Partitioned: true, // Available in newer Go versions + }) + } + + fmt.Printf("Cookie value: %s \n", cookie) + }) + + router.Run() +} +``` + +You can also use the `SetCookieData` method, which accepts a `*http.Cookie` directly for more flexibility: + +```go +import ( + "fmt" + "net/http" + "time" + + "github.com/gin-gonic/gin" +) + +func main() { + router := gin.Default() + + router.GET("/cookie", func(c *gin.Context) { cookie, err := c.Cookie("gin_cookie") if err != nil { cookie = "NotSet" - c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) + // Using http.Cookie struct for more control + c.SetCookieData(&http.Cookie{ + Name: "gin_cookie", + Value: "test", + Path: "/", + Domain: "localhost", + MaxAge: 3600, + Secure: false, + HttpOnly: true, + // Additional fields available in http.Cookie + Expires: time.Now().Add(24 * time.Hour), + // Partitioned: true, // Available in newer Go versions + }) } fmt.Printf("Cookie value: %s \n", cookie)