As of December 1st, 2019 Buffalo, and all related packages, require Go Modules and the use of the
GOPATH
is no longer supported.
Please see this blog post for more information https://blog.gobuffalo.io/the-road-to-1-0-requiring-modules-5672c6b015e5.
Cookies
An HTTP cookie is a small piece of data that a server sends to the user's web browser. The browser can store this data and send it back to the same server, even after the browser restart (unlike a browser session).
(HTTP) cookies are commonly used to save users state (like whether the user logged-in). See https://golang.org/pkg/net/http/#Cookie for more information on cookies in Go.
Setting a Cookie
func MyHandler(c buffalo.Context) error {
// ...
c.Cookies().Set("user_id", user.ID, 30 * 24 * time.Hour)
// ...
}
Setting a Cookie with Expiration
func MyHandler(c buffalo.Context) error {
// ...
exp := time.Now().Add(365 * 24 * time.Hour) // expire in 1 year
c.Cookies().SetWithExpirationTime("user_id", user.ID, exp)
// ...
}
Setting a Cookie with Path
func MyHandler(c buffalo.Context) error {
// ...
c.Cookies().SetWithPath("user_id", user.ID, "/user")
// ...
}
Advanced setting a Cookie way
import "net/http"
func MyHandler(c buffalo.Context) error {
// ...
ck := http.Cookie{
Name: "token",
Value: token,
Path: "/",
Expires: time.Now().Add(30 * 24 * time.Hour), // expire in 1 month
}
http.SetCookie(c.Response(), &ck)
// ...
}
See Cookie struct for other parameters.
Getting a Cookie
func MyHandler(c buffalo.Context) error {
value, err := c.Cookies().Get("user_id")
if err != nil {
return err
}
return c.Render(200, r.String(value))
}
Deleting a Cookie
func MyHandler(c buffalo.Context) error {
c.Cookies().Delete("user_id")
// ...
}
Feedback
If you found an error or something which needs to be improved, and you want to contribute to fix it:
If you'd like to suggest something to improve this page: