Repository navigation
Expand file tree
/
Copy pathforms.mojo
More file actions
69 lines (58 loc) · 2.13 KB
/
Copy pathforms.mojo
File metadata and controls
69 lines (58 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""Example 28: ``application/x-www-form-urlencoded`` forms.
Demonstrates the form-parsing surface:
- ``parse_form_urlencoded`` — bytes -> ``FormData`` multimap.
- ``urldecode`` / ``urlencode`` — WHATWG form encoding (``+``->space).
- ``Form`` extractor — typed-handler integration.
Run:
pixi run example-forms
"""
from flare.http import (
Form,
Method,
Request,
Response,
parse_form_urlencoded,
ok,
urldecode,
urlencode,
)
def main() raises:
print("=== flare Example 28: Forms ===")
print()
# ── 1. Parse a urlencoded body ─────────────────────────────────────────
print("── 1. parse_form_urlencoded ──")
var body = "user=alice+smith&age=30&interests=mojo&interests=rust"
var f = parse_form_urlencoded(body)
print(" bindings :", f.len())
print(" user :", f.get("user"))
print(" age :", f.get("age"))
var hobbies = f.get_all("interests")
print(" interests:", len(hobbies))
for i in range(len(hobbies)):
print(" -", hobbies[i])
print()
# ── 2. Encode / decode helpers ─────────────────────────────────────────
print("── 2. urlencode / urldecode ──")
var raw = "a&b=c d/e"
var enc = urlencode(raw)
var dec = urldecode(enc)
print(" raw :", raw)
print(" encoded :", enc)
print(" decoded :", dec)
print()
# ── 3. Form extractor (typical /login handler shape) ───────────────────
print("── 3. Form extractor ──")
var req = Request.test_post(
"/login",
"user=alice&pw=secret",
content_type="application/x-www-form-urlencoded",
)
var form = Form.extract(req)
print(" user :", form.value.get("user"))
print(" pw :", form.value.get("pw"))
print()
# Build the response a real handler might send.
var resp = ok("welcome " + form.value.get("user"))
print(" response :", resp.text())
print()
print("=== Example 28 complete ===")