Ver Fonte

Merge branch 'se77en-master' into develop

Javier Provecho Fernandez há 10 anos atrás
pai
commit
4892650ef8
2 ficheiros alterados com 52 adições e 0 exclusões
  1. 37 0
      context.go
  2. 15 0
      context_test.go

+ 37 - 0
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 {

+ 15 - 0
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) {