This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 579
/
cookies.go
73 lines (61 loc) · 1.97 KB
/
cookies.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package buffalo
import (
"net/http"
"time"
)
// Cookies allows you to easily get cookies from the request, and set cookies on the response.
type Cookies struct {
req *http.Request
res http.ResponseWriter
}
// 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.
func (c *Cookies) Get(name string) (string, error) {
ck, err := c.req.Cookie(name)
if err != nil {
return "", err
}
return ck.Value, nil
}
// Set a cookie on the response, which will expire after the given duration.
func (c *Cookies) Set(name, value string, maxAge time.Duration) {
ck := http.Cookie{
Name: name,
Value: value,
MaxAge: int(maxAge.Seconds()),
}
http.SetCookie(c.res, &ck)
}
// SetWithExpirationTime sets a cookie that will expire at a specific time.
// Note that the time is determined by the client's browser, so it might not expire at the expected time,
// for example if the client has changed the time on their computer.
func (c *Cookies) SetWithExpirationTime(name, value string, expires time.Time) {
ck := http.Cookie{
Name: name,
Value: value,
Expires: expires,
}
http.SetCookie(c.res, &ck)
}
// SetWithPath sets a cookie path on the server in which the cookie will be available on.
// If set to '/', the cookie will be available within the entire domain.
// If set to '/foo/', the cookie will only be available within the /foo/ directory and
// all sub-directories such as /foo/bar/ of domain.
func (c *Cookies) SetWithPath(name, value, path string) {
ck := http.Cookie{
Name: name,
Value: value,
Path: path,
}
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)
}