github.com/conradwt/buffalo@v0.11.1/cookies.go (about) 1 package buffalo 2 3 import ( 4 "net/http" 5 "time" 6 ) 7 8 // Cookies allows you to easily get cookies from the request, and set cookies on the response. 9 type Cookies struct { 10 req *http.Request 11 res http.ResponseWriter 12 } 13 14 // Get returns the value of the cookie with the given name. Returns http.ErrNoCookie if there's no cookie with that name in the request. 15 func (c *Cookies) Get(name string) (string, error) { 16 ck, err := c.req.Cookie(name) 17 if err != nil { 18 return "", err 19 } 20 21 return ck.Value, nil 22 } 23 24 // Set a cookie on the response, which will expire after the given duration. 25 func (c *Cookies) Set(name, value string, maxAge time.Duration) { 26 ck := http.Cookie{ 27 Name: name, 28 Value: value, 29 MaxAge: int(maxAge.Seconds()), 30 } 31 32 http.SetCookie(c.res, &ck) 33 } 34 35 // SetWithExpirationTime sets a cookie that will expire at a specific time. 36 // Note that the time is determined by the client's browser, so it might not expire at the expected time, 37 // for example if the client has changed the time on their computer. 38 func (c *Cookies) SetWithExpirationTime(name, value string, expires time.Time) { 39 ck := http.Cookie{ 40 Name: name, 41 Value: value, 42 Expires: expires, 43 } 44 45 http.SetCookie(c.res, &ck) 46 } 47 48 // Delete sets a header that tells the browser to remove the cookie with the given name. 49 func (c *Cookies) Delete(name string) { 50 ck := http.Cookie{ 51 Name: name, 52 Value: "v", 53 // Setting a time in the distant past, like the unix epoch, removes the cookie, 54 // since it has long expired. 55 Expires: time.Unix(0, 0), 56 } 57 58 http.SetCookie(c.res, &ck) 59 }