diff --git a/context.go b/context.go index c885cf1b..a4ca9f32 100644 --- a/context.go +++ b/context.go @@ -10,6 +10,7 @@ import ( "math" "net" "net/http" + "net/url" "strings" "time" @@ -325,6 +326,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, error) { + cookie, err := c.Request.Cookie(name) + if err != nil { + return "", err + } + val, _ := url.QueryUnescape(cookie.Value) + return val, nil +} + 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 55377b7c..3deecadb 100644 --- a/context_test.go +++ b/context_test.go @@ -238,6 +238,21 @@ func TestContextPostFormMultipart(t *testing.T) { assert.Equal(t, c.PostForm("bar"), "foo") } +func TestContextSetCookie(t *testing.T) { + c, _, _ := createTestContext() + c.SetCookie("user", "gin", 1, "/", "localhost", true, true) + c.Request, _ = http.NewRequest("GET", "/set", nil) + assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure") +} + +func TestContextGetCookie(t *testing.T) { + c, _, _ := createTestContext() + c.Request, _ = http.NewRequest("GET", "/get", nil) + c.Request.Header.Set("Cookie", "user=gin") + cookie, _ := c.GetCookie("user") + assert.Equal(t, cookie, "gin") +} + // Tests that the response is serialized as JSON // and Content-Type is set to application/json func TestContextRenderJSON(t *testing.T) {