diff --git a/context.go b/context.go index b784c14..4bf7986 100644 --- a/context.go +++ b/context.go @@ -9,6 +9,7 @@ import ( "io" "math" "net/http" + "net/url" "strings" "time" @@ -321,6 +322,42 @@ func (c *Context) Header(key, value string) { } } +func (c *Context) SetCookie( + name string, + value string, + maxAge int, + path string, + domain string, + secure bool, + httpOnly bool, +) { + cookie := http.Cookie{} + cookie.Name = name + cookie.Value = url.QueryEscape(value) + + cookie.MaxAge = maxAge + + cookie.Path = "/" + if path != "" { + cookie.Path = path + } + + cookie.Domain = domain + cookie.Secure = secure + cookie.HttpOnly = httpOnly + + c.Writer.Header().Add("Set-Cookie", cookie.String()) +} + +func (c *Context) GetCookie(name string) string { + cookie, err := c.Request.Cookie(name) + if err != nil { + return "" + } + val, _ := url.QueryUnescape(cookie.Value) + return val +} + func (c *Context) Render(code int, r render.Render) { c.writermem.WriteHeader(code) if err := r.Render(c.Writer); err != nil { diff --git a/context_test.go b/context_test.go index 169768b..18e5460 100644 --- a/context_test.go +++ b/context_test.go @@ -247,6 +247,23 @@ func TestContextPostFormMultipart(t *testing.T) { assert.Equal(t, c.PostForm("bar"), "foo") } +func TestContextSetCookie(t *testing.T) { + c, w, _ := createTestContext() + c.SetCookie("user", "gin", 1, "/", "localhost", true, true) + c.SetCookie("user", "gin", int32(1), "/", "localhost", 1) + c.SetCookie("user", "gin", int64(1)) + + c.Request, _ = http.NewRequest("GET", "/set", nil) + assert.Equal(t, c.GetCookie("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure") +} + +func TestContextGetCookie(t *testing.T) { + c, w, _ := createTestContext() + c.Request, _ = http.NewRequest("GET", "/get", nil) + c.Request.Header.Set("Cookie", "user=gin") + assert.Equal(t, c.GetCookie("Cookie"), "gin") +} + // Tests that the response is serialized as JSON // and Content-Type is set to application/json func TestContextRenderJSON(t *testing.T) {