Skip to content
Myr

feat(context): add SetCookieData (#4240)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* 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

authored by NARITA · committed by GitHub · parent 3d8e288 · Browse files · 3 files+192 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+192 added−1 removed

  • other:+192 added−1 removed

3 files+192 added−1 removed

modified:docs/doc.md+53 added-1 removed
2302 unmodified lines
2303func main() {2304 router := gin.Default()23052306 router.GET("/cookie", func(c *gin.Context) {2307 cookie, err := c.Cookie("gin_cookie")23082309 if err != nil {2310 cookie = "NotSet"2311 // Using http.Cookie struct for more control2312 c.SetCookieData(&http.Cookie{2313 Name: "gin_cookie",2314 Value: "test",2315 Path: "/",2316 Domain: "localhost",2317 MaxAge: 3600,2318 Secure: false,2319 HttpOnly: true,2320 // Additional fields available in http.Cookie2321 Expires: time.Now().Add(24 * time.Hour),2322 // Partitioned: true, // Available in newer Go versions2323 })2324 }23252326 fmt.Printf("Cookie value: %s \n", cookie)2327 })23282329 router.Run()2330}2331```23322333You can also use the `SetCookieData` method, which accepts a `*http.Cookie` directly for more flexibility:23342335```go2336import (2337 "fmt"2338 "net/http"2339 "time"23402341 "github.com/gin-gonic/gin"2342)23432344func main() {2345 router := gin.Default()23462347 router.GET("/cookie", func(c *gin.Context) {2348 cookie, err := c.Cookie("gin_cookie")23492350 if err != nil {2351 cookie = "NotSet"2312 c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)2352 // Using http.Cookie struct for more control2353 c.SetCookieData(&http.Cookie{2354 Name: "gin_cookie",2355 Value: "test",2356 Path: "/",2357 Domain: "localhost",2358 MaxAge: 3600,2359 Secure: false,2360 HttpOnly: true,2361 // Additional fields available in http.Cookie2362 Expires: time.Now().Add(24 * time.Hour),2363 // Partitioned: true, // Available in newer Go versions2364 })2365 }23662367 fmt.Printf("Cookie value: %s \n", cookie)2368 })
129 unmodified lines
modified:context_test.go+126 added
3121 unmodified lines
3122 value, exists = c.Get("key3")3123 assert.True(t, exists)3124 assert.Equal(t, "value3", value)3125}31263127func TestContextSetCookieData(t *testing.T) {3128 c, _ := CreateTestContext(httptest.NewRecorder())3129 c.SetSameSite(http.SameSiteLaxMode)3130 var setCookie string31313132 // Basic cookie settings3133 cookie := &http.Cookie{3134 Name: "user",3135 Value: "gin",3136 MaxAge: 1,3137 Path: "/",3138 Domain: "localhost",3139 Secure: true,3140 HttpOnly: true,3141 }3142 c.SetCookieData(cookie)3143 setCookie = c.Writer.Header().Get("Set-Cookie")3144 assert.Contains(t, setCookie, "user=gin")3145 assert.Contains(t, setCookie, "Path=/")3146 assert.Contains(t, setCookie, "Domain=localhost")3147 assert.Contains(t, setCookie, "Max-Age=1")3148 assert.Contains(t, setCookie, "HttpOnly")3149 assert.Contains(t, setCookie, "Secure")3150 // SameSite=Lax might be omitted in Go 1.23+ as it's the default3151 // assert.Contains(t, setCookie, "SameSite=Lax")31523153 // Test that when Path is empty, "/" is automatically set3154 cookie = &http.Cookie{3155 Name: "user",3156 Value: "gin",3157 MaxAge: 1,3158 Path: "",3159 Domain: "localhost",3160 Secure: true,3161 HttpOnly: true,3162 }3163 c.SetCookieData(cookie)3164 setCookie = c.Writer.Header().Get("Set-Cookie")3165 assert.Contains(t, setCookie, "user=gin")3166 assert.Contains(t, setCookie, "Path=/")3167 assert.Contains(t, setCookie, "Domain=localhost")3168 assert.Contains(t, setCookie, "Max-Age=1")3169 assert.Contains(t, setCookie, "HttpOnly")3170 assert.Contains(t, setCookie, "Secure")3171 // SameSite=Lax might be omitted in Go 1.23+ as it's the default3172 // assert.Contains(t, setCookie, "SameSite=Lax")31733174 // Test additional cookie attributes (Expires)3175 expireTime := time.Now().Add(24 * time.Hour)3176 cookie = &http.Cookie{3177 Name: "user",3178 Value: "gin",3179 Path: "/",3180 Domain: "localhost",3181 Expires: expireTime,3182 Secure: true,3183 HttpOnly: true,3184 }3185 c.SetCookieData(cookie)31863187 // Since the Expires value varies by time, partially verify with Contains3188 setCookie = c.Writer.Header().Get("Set-Cookie")3189 assert.Contains(t, setCookie, "user=gin")3190 assert.Contains(t, setCookie, "Path=/")3191 assert.Contains(t, setCookie, "Domain=localhost")3192 assert.Contains(t, setCookie, "HttpOnly")3193 assert.Contains(t, setCookie, "Secure")3194 // SameSite=Lax might be omitted in Go 1.23+ as it's the default3195 // assert.Contains(t, setCookie, "SameSite=Lax")31963197 // Test for Partitioned attribute (Go 1.18+)3198 cookie = &http.Cookie{3199 Name: "user",3200 Value: "gin",3201 Path: "/",3202 Domain: "localhost",3203 Secure: true,3204 HttpOnly: true,3205 Partitioned: true,3206 }3207 c.SetCookieData(cookie)3208 setCookie = c.Writer.Header().Get("Set-Cookie")3209 assert.Contains(t, setCookie, "user=gin")3210 assert.Contains(t, setCookie, "Path=/")3211 assert.Contains(t, setCookie, "Domain=localhost")3212 assert.Contains(t, setCookie, "HttpOnly")3213 assert.Contains(t, setCookie, "Secure")3214 // SameSite=Lax might be omitted in Go 1.23+ as it's the default3215 // assert.Contains(t, setCookie, "SameSite=Lax")3216 // Not testing for Partitioned attribute as it may not be supported in all Go versions32173218 // Test that SameSiteStrictMode is explicitly included in the header3219 t.Run("SameSite=Strict is included", func(t *testing.T) {3220 c, _ := CreateTestContext(httptest.NewRecorder())3221 cookie := &http.Cookie{3222 Name: "user",3223 Value: "gin",3224 Path: "/",3225 Domain: "localhost",3226 Secure: true,3227 HttpOnly: true,3228 SameSite: http.SameSiteStrictMode,3229 }3230 c.SetCookieData(cookie)3231 setCookie := c.Writer.Header().Get("Set-Cookie")3232 assert.Contains(t, setCookie, "SameSite=Strict")3233 })32343235 // Test that SameSiteNoneMode is explicitly included in the header3236 t.Run("SameSite=None is included", func(t *testing.T) {3237 c, _ := CreateTestContext(httptest.NewRecorder())3238 cookie := &http.Cookie{3239 Name: "user",3240 Value: "gin",3241 Path: "/",3242 Domain: "localhost",3243 Secure: true,3244 HttpOnly: true,3245 SameSite: http.SameSiteNoneMode,3246 }3247 c.SetCookieData(cookie)3248 setCookie := c.Writer.Header().Get("Set-Cookie")3249 assert.Contains(t, setCookie, "SameSite=None")3250 })3251}
modified:context.go+13 added
1025 unmodified lines
1026 HttpOnly: httpOnly,1027 })1028}10291030// SetCookieData adds a Set-Cookie header to the ResponseWriter's headers.1031// It accepts a pointer to http.Cookie structure for more flexibility in setting cookie attributes.1032// The provided cookie must have a valid Name. Invalid cookies may be silently dropped.1033func (c *Context) SetCookieData(cookie *http.Cookie) {1034 if cookie.Path == "" {1035 cookie.Path = "/"1036 }1037 if cookie.SameSite == http.SameSiteDefaultMode {1038 cookie.SameSite = c.sameSite1039 }1040 http.SetCookie(c.Writer, cookie)1041}10421043// Cookie returns the named cookie provided in the request or1044// ErrNoCookie if not found. And return the named cookie is unescaped.1045// If multiple cookies match the given name, only one cookie will1046// be returned.
327 unmodified lines