HTTP/1.1 200 OK
Set-Cookie: session_id=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=LaxGET /api/profile HTTP/1.1
Cookie: session_id=abc123; theme=dark| Attribute | Purpose |
|---|---|
| Max-Age | Seconds until the cookie expires. 0 deletes it immediately. |
| Path | URL path prefix the cookie applies to (default: current path). |
| Domain | Which hosts receive the cookie (default: exact origin only). |
| Secure | Only send over HTTPS. |
| HttpOnly | Hide from JavaScript (document.cookie), mitigating XSS. |
| SameSite | Controls cross-site sending — see SameSite Options. |
import {
"bobzhang/crescent/cookie"
...
}///|
test "create a cookie with attributes" {
let cookie = @cookie.CookieItem(
name="session_id",
value="abc123",
max_age=3600,
path="/",
domain="example.com",
secure=true,
http_only=true,
same_site=Lax,
)
debug_inspect(
cookie,
content=(
#|{
#| name: "session_id",
#| value: "abc123",
#| max_age: Some(3600),
#| path: Some("/"),
#| domain: Some("example.com"),
#| secure: Some(true),
#| http_only: Some(true),
#| same_site: Some(Lax),
#|}
),
)
}///|
test "minimal cookie" {
let cookie = @cookie.CookieItem(name="theme", value="dark")
debug_inspect(
cookie.to_string(),
content=(
#|"theme=dark"
),
)
}///|
test "parse a cookie header" {
let cookies = @cookie.parse_cookie("name=value; session=abc123")
debug_inspect(
cookies.get("name").map(fn(c) { c.value }),
content="Some(\"value\")",
)
debug_inspect(
cookies.get("session").map(fn(c) { c.value }),
content="Some(\"abc123\")",
)
}///|
test "parse cookie with attributes" {
let cookies = @cookie.parse_cookie(
"token=xyz; Path=/api; Secure; HttpOnly; SameSite=Strict",
)
guard cookies.get("token") is Some(c) else { fail("expected token cookie") }
assert_eq(c.path, Some("/api"))
assert_eq(c.secure, Some(true))
assert_eq(c.http_only, Some(true))
assert_eq(c.same_site, Some(Strict))
}///|
test "serialize multiple cookies" {
let cookies = [
@cookie.CookieItem(name="a", value="1"),
CookieItem(name="b", value="2"),
]
debug_inspect(
@cookie.cookie_to_string(cookies),
content=(
#|"a=1;b=2"
),
)
}| Variant | Meaning |
|---|---|
| Lax | Sent on top-level navigations and GET requests |
| Strict | Sent only on same-site requests |
| SameSiteNone | Sent on all requests (requires Secure) |
pub(all) struct CookieItem {
name : String
value : String
max_age : Int?
path : String?
domain : String?
secure : Bool?
http_only : Bool?
same_site : SameSiteOption?
} derive(Eq, Debug)impl Show for CookieItemfn CookieItem::CookieItem(name~ : String, value~ : String, max_age? : Int, path? : String, domain? : String, secure? : Bool, http_only? : Bool, same_site? : SameSiteOption) -> CookieItemimpl Show for SameSiteOptionimpl ToJson for SameSiteOptionCrescent: A web framework for MoonBit.
Dependencies