From 1684e471ae871e63734596995bd2c98ed250c905 Mon Sep 17 00:00:00 2001 From: Frederik Creemers Date: Sat, 29 Jul 2017 20:01:56 +0200 Subject: [PATCH] Add Cookies.Delete method --- cookies.go | 13 +++++++++++++ cookies_test.go | 12 ++++++++++++ 2 files changed, 25 insertions(+) diff --git a/cookies.go b/cookies.go index eeac1a856..131317a64 100644 --- a/cookies.go +++ b/cookies.go @@ -44,3 +44,16 @@ func (c *Cookies) SetWithExpirationTime(name, value string, expires time.Time) { http.SetCookie(c.res, &ck) } + +// Delete sets a header that tells the browser to remove the cookie with the given name. +func (c *Cookies) Delete(name string) { + ck := http.Cookie{ + Name: name, + Value: "v", + // Setting a time in the distant past, like the unix epoch, removes the cookie, + // since it has long expired. + Expires: time.Unix(0, 0), + } + + http.SetCookie(c.res, &ck) +} diff --git a/cookies_test.go b/cookies_test.go index fa45bdefe..67a7306fe 100644 --- a/cookies_test.go +++ b/cookies_test.go @@ -51,3 +51,15 @@ func TestCookies_SetWithExpirationTime(t *testing.T) { h := res.Header().Get("Set-Cookie") r.Equal("name=Rob Pike; Expires=Sat, 29 Jul 2017 19:28:45 GMT", h) } + +func TestCookies_Delete(t *testing.T) { + r := require.New(t) + res := httptest.NewRecorder() + + c := Cookies{&http.Request{}, res} + + c.Delete("remove-me") + + h := res.Header().Get("Set-Cookie") + r.Equal("remove-me=v; Expires=Thu, 01 Jan 1970 00:00:00 GMT", h) +}