feat(context): add SetCookieData (#4240)

* 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
This commit is contained in:
NARITA
2025-05-21 09:20:44 +09:00
committed by GitHub
parent 3d8e288c64
commit fb09c825e8
3 changed files with 192 additions and 1 deletions
+53 -1
View File
@@ -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)