Skip to content

Commit

Permalink
feat: add cookie support
Browse files Browse the repository at this point in the history
  • Loading branch information
zjregee committed Aug 26, 2024
1 parent 92a2c5e commit 9352546
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions ahttp/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
24 changes: 24 additions & 0 deletions ahttp/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -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"))
Expand Down

0 comments on commit 9352546

Please sign in to comment.