diff --git a/ahttp/context.go b/ahttp/context.go index 31f8ecc..1097e45 100644 --- a/ahttp/context.go +++ b/ahttp/context.go @@ -40,6 +40,18 @@ func (c *Context) Response() http.ResponseWriter { return c.response } +func (c *Context) Cookie(name string) (*http.Cookie, error) { + return c.request.Cookie(name) +} + +func (c *Context) SetCookie(cookie *http.Cookie) { + http.SetCookie(c.response, cookie) +} + +func (c *Context) Cookies() []*http.Cookie { + return c.request.Cookies() +} + func (c *Context) QueryParam(name string) string { if c.query == nil { c.query = c.request.URL.Query() diff --git a/ahttp/context_test.go b/ahttp/context_test.go index 8cb6764..ae6a474 100644 --- a/ahttp/context_test.go +++ b/ahttp/context_test.go @@ -5,6 +5,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/stretchr/testify/assert" ) @@ -49,6 +50,29 @@ func TestContextResponse(t *testing.T) { assert.NotNil(t, c.Response()) } +func TestContextCookie(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + req.Header.Add("Cookie", "name=test") + req.Header.Add("Cookie", "age=18") + c := newContext(req, rec) + for _, cookie := range c.Cookies() { + assert.Contains(t, []string{"name", "age"}, cookie.Name) + assert.Contains(t, []string{"test", "18"}, cookie.Value) + } + cookie := &http.Cookie{ + Name: "name", + Value: "test", + Expires: time.Now().Add(24 * time.Hour), + Secure: true, + HttpOnly: true, + } + c.SetCookie(cookie) + assert.Contains(t, rec.Header().Get("Set-Cookie"), "name=test") + assert.Contains(t, rec.Header().Get("Set-Cookie"), "Secure") + assert.Contains(t, rec.Header().Get("Set-Cookie"), "HttpOnly") +} + func TestContextQueryParam(t *testing.T) { c := newTestContextWithJson() assert.Equal(t, "test", c.QueryParam("name"))