Getting Started
CLI
Request handling
- Routing
- Action Controller
- Resources
- Context
- Request Binding
- Middleware
- Error Handling
- Sessions
- Cookies
Frontend
Database
- Getting started with Pop
- Soda CLI
- Database Configuration
- Buffalo Integration
- Models
- Generators
- Migrations
- Fizz
- Mutations
- Querying
- Raw Queries
- Callbacks
- Scoping
- Associations and Relationships
- One to one associations
- One to many associations
Guides
- API Applications
- File Uploads
- Background Job Workers
- Mailers
- Tasks
- Local Authentication
- Third Party Authentication
- Events
- Go Modules
- Localization
- Logging
- Template Engines
- Testing
- Videos
Deploy
Cookies
Request handling
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")
// ...
}