Cookies are a simple way to remember users, track sessions, or save preferences like language or theme. Mizu provides two helpers,
Ctx.Cookie() and Ctx.SetCookie(), that make cookie handling easy.
Code
Create a file namedmain.go and add this code:
Run
Start the server:Set a cookie
Visit http://localhost:8080/set?name=Alice Response:Cookie set for Alice
Your browser now stores a cookie named username.
Get the cookie
Visit http://localhost:8080/get Response:Welcome back, Alice
The value comes from the cookie you set earlier.
Clear the cookie
Visit http://localhost:8080/clear Response:Cookie cleared
The browser cookie is now deleted.
How it works
| Method | Purpose | Example |
|---|---|---|
c.SetCookie(ck *http.Cookie) | Sends a cookie to the client | Sets name, value, expiry, and options like HttpOnly or Secure. |
c.Cookie("name") | Reads a cookie sent by the client | Returns a *http.Cookie and an error if not found. |
- Setting a cookie adds a
Set-Cookieheader to the HTTP response. - Reading a cookie checks the request headers for the matching cookie name.
- Deleting a cookie works by sending a new cookie with an empty value and an expiration date in the past.
Try something new
Add a handler that counts how many times a user has visited your site:app.Get("/visits", visitCount) and refresh the page several times.
The count will increase with each visit.
Cookies form the basis for session handling, login tracking, and simple user personalization.
Next, continue to Middleware Basics to learn how to wrap your handlers with reusable logic like logging, timing, and authentication.