Skip to content

Commit

Permalink
implement cookie helper function to context (#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
acoshift authored Sep 27, 2023
1 parent 0fdbd44 commit 0885a54
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
48 changes: 48 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,54 @@ func (ctx *Context) BindJSON(v any) error {
return json.NewDecoder(ctx.Body).Decode(v)
}

type CookieOptions struct {
Path string
Domain string
MaxAge int
Secure bool
HttpOnly bool
SameSite http.SameSite
}

func (ctx *Context) AddCookie(name string, value string, opts *CookieOptions) {
c := http.Cookie{
Name: name,
Value: value,
}
if opts != nil {
c.Path = opts.Path
c.Domain = opts.Domain
c.MaxAge = opts.MaxAge
c.Secure = opts.Secure
c.HttpOnly = opts.HttpOnly
c.SameSite = opts.SameSite
}
http.SetCookie(ctx.w, &c)
}

func (ctx *Context) DelCookie(name string, opts *CookieOptions) {
c := http.Cookie{
Name: name,
MaxAge: -1,
}
if opts != nil {
c.Path = opts.Path
c.Domain = opts.Domain
c.Secure = opts.Secure
c.HttpOnly = opts.HttpOnly
c.SameSite = opts.SameSite
}
http.SetCookie(ctx.w, &c)
}

func (ctx *Context) CookieValue(name string) string {
c, _ := ctx.Cookie(name)
if c == nil {
return ""
}
return c.Value
}

func etag(b []byte) string {
hash := sha1.Sum(b)
l := len(b)
Expand Down
20 changes: 20 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -835,4 +835,24 @@ func TestContext(t *testing.T) {
assert.NoError(t, ctx.BindJSON(&body))
assert.Equal(t, 1, body.A)
})

t.Run("Cookie", func(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/", nil)
r.AddCookie(&http.Cookie{Name: "a", Value: "1"})

app := hime.New()
ctx := hime.NewAppContext(app, w, r)

assert.Equal(t, "1", ctx.CookieValue("a"))

ctx.AddCookie("b", "2", &hime.CookieOptions{Path: "/"})
ctx.DelCookie("a", nil)

if !assert.Len(t, w.Header()["Set-Cookie"], 2) {
return
}
assert.Equal(t, "b=2; Path=/", w.Header()["Set-Cookie"][0])
assert.Equal(t, "a=; Max-Age=0", w.Header()["Set-Cookie"][1])
})
}

0 comments on commit 0885a54

Please sign in to comment.