github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/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 // SetWithPath sets a cookie path on the server in which the cookie will be available on. 49 // If set to '/', the cookie will be available within the entire domain. 50 // If set to '/foo/', the cookie will only be available within the /foo/ directory and 51 // all sub-directories such as /foo/bar/ of domain. 52 func (c *Cookies) SetWithPath(name, value, path string) { 53 ck := http.Cookie{ 54 Name: name, 55 Value: value, 56 Path: path, 57 } 58 59 http.SetCookie(c.res, &ck) 60 } 61 62 // Delete sets a header that tells the browser to remove the cookie with the given name. 63 func (c *Cookies) Delete(name string) { 64 ck := http.Cookie{ 65 Name: name, 66 Value: "v", 67 // Setting a time in the distant past, like the unix epoch, removes the cookie, 68 // since it has long expired. 69 Expires: time.Unix(0, 0), 70 } 71 72 http.SetCookie(c.res, &ck) 73 }