Cookie
cookie reads one cookie value from the current HTTP request.
Overview
Use cookie when a Goblin HTTP handler needs a value from the request's Cookie header:
session_id | cookie("session_id") if session_id :say("welcome back") else :say("no session") end
session_id | cookie("session_id") if session_id :say("welcome back") else :say("no session") end
cookie returns the cookie value as a string. If the cookie is not present, it returns nil.
Reading a Cookie
Pass the cookie name as a string:
theme | cookie("theme") :say(theme)
theme | cookie("theme") :say(theme)
If the incoming request has this header:
Cookie: theme=dark; session_id=abc123
Cookie: theme=dark; session_id=abc123
Then:
:say(cookie("theme")) /// dark :say(cookie("session_id")) /// abc123
:say(cookie("theme")) /// dark :say(cookie("session_id")) /// abc123
Missing Cookies
When the cookie is not present, cookie returns nil:
coupon | cookie("coupon") :say(coupon) /// nil
coupon | cookie("coupon") :say(coupon) /// nil
That makes it easy to branch:
if coupon :say("coupon found") else :say("no coupon") end
if coupon :say("coupon found") else :say("no coupon") end
Name Matching
Cookie names are matched exactly:
cookie("session_id")
cookie("session_id")
This looks for session_id, not Session_Id or SESSION_ID.
The HTTP header name itself is case-insensitive, so Cookie and cookie are both recognized as the incoming cookie header.
Raw Values
cookie returns the raw value from the cookie header:
Cookie: name=Dana%20Scully
Cookie: name=Dana%20Scully
:say(cookie("name")) /// Dana%20Scully
:say(cookie("name")) /// Dana%20Scully
It does not URL-decode, JSON-parse, decrypt, or verify the cookie value for you.
Request Context
cookie reads from the current request environment. In Goblin's HTTP runtime, request headers are made available to Goblin before your handler runs.
Outside an HTTP request, there may be no cookie header:
:say(cookie("session_id")) /// nil
:say(cookie("session_id")) /// nil
Use req_header("cookie") when you need the full raw Cookie header instead of one parsed value.
Cookie vs Set Cookie
cookie reads a cookie from the incoming request:
session_id | cookie("session_id")
session_id | cookie("session_id")
set_cookie writes a cookie to the outgoing response:
set_cookie("theme", "dark")
set_cookie("theme", "dark")
Reading and writing cookies are separate operations.
Signature
cookie(name)
cookie(name)
| Argument | Type | Description |
|---|---|---|
name |
string | The cookie name to read. |
Returns the cookie value as a string, or nil when the cookie is not present.
Errors
cookie requires exactly one argument:
cookie() /// error: R0301 wrong-arity cookie("theme", "fallback") /// error: R0301 wrong-arity
cookie() /// error: R0301 wrong-arity cookie("theme", "fallback") /// error: R0301 wrong-arity
The cookie name must be a string:
cookie(42) /// error: T0205 type-mismatch
cookie(42) /// error: T0205 type-mismatch
A missing cookie is not an error; it returns nil.