HTTP Module
The std/http module provides everything you need for HTTP in Chuks: a high-performance server with routing and middleware, typed Request/Response objects, and an asynchronous HTTP client.
Import
Section titled “Import”// Server + typesimport { createServer, Request, Response } from "std/http"
// HTTP clientimport { http } from "std/http"
// All exportsimport { createServer, Request, Response, http, HttpResponse } from "std/http"Module Exports
Section titled “Module Exports”| Export | Kind | Description |
|---|---|---|
createServer | function | Create an HTTP server instance (HttpServer) |
Request | dataType | Incoming request object passed to route handlers |
Response | dataType | Outgoing response object passed to route handlers |
UploadedFile | dataType | Uploaded file from multipart/form-data requests |
http | HTTP | HTTP client instance for outbound requests |
HTTP | class | HTTP client class |
HttpResponse | dataType | Response returned by HTTP client calls |
Server Types
Section titled “Server Types”Request
Section titled “Request”The Request object is the first argument to every route handler and middleware.
dataType Request { method: string // HTTP method (GET, POST, etc.) path: string // Request path (e.g. "/users/123") body: string // Raw request body params: map[string]string // Route parameters (e.g. { id: "123" }) query: map[string]string // Query string parameters headers: map[string]string // Request headers (keys lowercased) ip: string // Client IP address originalUrl: string // Full URL path + query string protocol: string // "http" or "https" hostname: string // Hostname from Host header (port stripped) secure: bool // true when protocol is "https" userAgent: string // User-Agent header value contentType: string // Content-Type header value referer: string // Referer header value cookies: map[string]string // All cookies as key-value pairs formData: map[string]string // Parsed form fields from multipart requests files: []UploadedFile // Uploaded files from multipart/form-data}Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
method | string | HTTP method (GET, POST, etc.) |
path | string | Request path (e.g. “/users/123”) |
body | string | Raw request body |
params | map[string]string | Route parameters (e.g. { id: "123" }) |
query | map[string]string | Query string parameters |
headers | map[string]string | Request headers (keys lowercased) |
ip | string | Client IP address (e.g. “127.0.0.1”) |
originalUrl | string | Full URL path + query string (e.g. “/users?page=1”) |
protocol | string | Protocol string — “http” or “https” |
hostname | string | Hostname from Host header, port stripped |
secure | bool | Shorthand for protocol == "https" |
userAgent | string | Value of the User-Agent header |
contentType | string | Value of the Content-Type header |
referer | string | Value of the Referer header |
cookies | map[string]string | All cookies as key-value pairs |
formData | map[string]string | Parsed form fields from multipart requests |
files | []UploadedFile | Uploaded files from multipart/form-data requests |
Methods
Section titled “Methods”| Method | Return | Description |
|---|---|---|
header(name) | string | Get a specific header value (case-insensitive) |
cookie(name) | string | Get a cookie value by name |
parseBody(Type?) | any | Parse JSON body, optionally into a typed dataType |
app.post("/api/data", function(req: Request, res: Response) { const contentType = req.header("Content-Type") const body = req.body const search = req.query["q"] const userId = req.params["id"] const clientIp = req.ip const fullUrl = req.originalUrl res.json('{"received": true}')})Parsing Request Bodies
Section titled “Parsing Request Bodies”parseBody() parses the raw JSON body string into a Chuks value. When called with a dataType argument, it returns a typed instance:
dataType CreateUserRequest { name: string email: string}
app.post("/api/users", function(req: Request, res: Response) { // Untyped — returns a generic map const data = req.parseBody() println(data["name"])
// Typed — returns a CreateUserRequest instance const user = req.parseBody(CreateUserRequest) println(user.name) println(user.email) res.status(201).json('{"created": true}')})Reading Cookies
Section titled “Reading Cookies”app.get("/dashboard", function(req: Request, res: Response) { const sessionId = req.cookie("session_id") if (sessionId == "") { res.redirect("/login") return } res.send("Welcome back!")})Convenience Properties
Section titled “Convenience Properties”Common header values are available directly on the request:
app.post("/api/data", function(req: Request, res: Response) { println(req.userAgent) // e.g. "Mozilla/5.0 ..." println(req.contentType) // e.g. "application/json" println(req.referer) // e.g. "https://example.com"
// All cookies as a typed map var cookies: map[string]string = req.cookies println(cookies["session_id"])})File Uploads (multipart/form-data)
Section titled “File Uploads (multipart/form-data)”When a request is sent as multipart/form-data, Chuks automatically parses form fields into req.formData and uploaded files into req.files.
import { createServer, Request, Response, UploadedFile } from "std/http"
const app = createServer()
app.post("/upload", function(req: Request, res: Response) { // Access form fields var name: string = req.formData["name"]
// Access uploaded files var fileCount: int = req.files.length if (fileCount > 0) { var f: UploadedFile = req.files[0] println(f.fileName) // e.g. "photo.jpg" println(f.contentType) // e.g. "image/jpeg" println(f.size) // file size in bytes println(f.extension) // e.g. ".jpg" println(f.data) // raw file content } res.json('{"uploaded": true}')})
app.listen(3000)UploadedFile
Section titled “UploadedFile”Represents an uploaded file from a multipart/form-data request.
dataType UploadedFile { fieldName: string // Form field name (e.g. "avatar") fileName: string // Original filename (e.g. "photo.jpg") contentType: string // MIME type (e.g. "image/jpeg") size: int // File size in bytes data: string // Raw file content extension: string // File extension including dot (e.g. ".jpg")}| Property | Type | Description |
|---|---|---|
fieldName | string | Form field name (e.g. “avatar”) |
fileName | string | Original filename (e.g. “photo.jpg”) |
contentType | string | MIME type (e.g. “image/jpeg”) |
size | int | File size in bytes |
data | string | Raw file content as a string |
extension | string | File extension including dot (e.g. “.jpg”, “.png”) |
Response
Section titled “Response”The Response object is the second argument to every route handler and middleware. All methods are chainable.
dataType Response { statusCode: int // HTTP status code (default 200) body: string // Response body}| Method | Return | Description |
|---|---|---|
res.status(code: int) | Response | Set the HTTP status code |
res.header(key, value) | Response | Set a response header |
res.json(body: any) | Response | Send JSON response (sets Content-Type: application/json) |
res.send(body: string) | Response | Send plain text response |
res.redirect(url, status?) | Response | Redirect to URL (default 302). Sets Location header |
res.type(contentType) | Response | Set Content-Type with shorthand (json, html, text, xml, form) |
res.cookie(name, value, options?) | Response | Set a cookie. Options: maxAge, httpOnly, secure, sameSite, path, domain |
res.clearCookie(name) | Response | Clear a cookie (expires it via Max-Age=0) |
app.get("/api/user", function(req: Request, res: Response) { res.status(200) .header("X-Request-Id", "abc123") .json('{"name": "Alice"}')})Redirects
Section titled “Redirects”app.get("/old-page", function(req: Request, res: Response) { res.redirect("/new-page") // 302 Found (default)})
app.get("/moved", function(req: Request, res: Response) { res.redirect("/permanent-new", 301) // 301 Moved Permanently})Content-Type Shorthand
Section titled “Content-Type Shorthand”res.type() supports convenient shorthand aliases:
| Shorthand | Expands to |
|---|---|
json | application/json |
html | text/html |
text | text/plain |
xml | application/xml |
form | application/x-www-form-urlencoded |
app.get("/page", function(req: Request, res: Response) { res.type("html").send("<h1>Hello</h1>")})Setting and Clearing Cookies
Section titled “Setting and Clearing Cookies”app.post("/login", function(req: Request, res: Response) { res.cookie("session_id", "abc123", { "maxAge": 86400, "httpOnly": true, "secure": true, "sameSite": "Strict", "path": "/" }).json('{"loggedIn": true}')})
app.post("/logout", function(req: Request, res: Response) { res.clearCookie("session_id").json('{"loggedOut": true}')})HttpServer
Section titled “HttpServer”Created by createServer(). All methods are chainable.
| Method | Signature | Description |
|---|---|---|
use | use(handler) → HttpServer | Register a middleware |
get | get(path, handler) → HttpServer | Register GET route |
post | post(path, handler) → HttpServer | Register POST route |
put | put(path, handler) → HttpServer | Register PUT route |
delete | delete(path, handler) → HttpServer | Register DELETE route |
patch | patch(path, handler) → HttpServer | Register PATCH route |
all | all(path, handler) → HttpServer | Register catch-all route |
listen | listen(port) → void | Start server on given port |
close | close() → void | Graceful shutdown |
import { createServer, Request, Response } from "std/http"
const app = createServer()
app.use(function(req: Request, res: Response, next: any) { res.header("X-Powered-By", "Chuks") next()})
app.get("/", function(req: Request, res: Response) { res.json('{"status": "ok"}')})
app.listen(3000)For the full server guide (routing, middleware patterns, configuration, context integration, and benchmarks), see the HTTP Server guide.
Client Functions
Section titled “Client Functions”http.get(url: string, headers?: map): Task<HttpResponse>
Section titled “http.get(url: string, headers?: map): Task<HttpResponse>”Performs an asynchronous GET request. An optional headers map can be passed as the second argument.
const resp = await http.get("https://api.example.com/data")println(resp.status) // 200println(resp.body) // Response body string
// With custom headersconst resp2 = await http.get("https://api.example.com/data", { "Authorization": "Bearer token123"})http.post(url: string, body: string, contentType?: string): Task<HttpResponse>
Section titled “http.post(url: string, body: string, contentType?: string): Task<HttpResponse>”Performs an asynchronous POST request. An optional content type can be passed as the third argument.
const resp = await http.post( "https://api.example.com/users", '{"name": "Alice"}')println(resp.status) // 201http.put(url: string, body: string, contentType?: string): Task<HttpResponse>
Section titled “http.put(url: string, body: string, contentType?: string): Task<HttpResponse>”Performs an asynchronous PUT request.
const resp = await http.put( "https://api.example.com/users/1", '{"name": "Bob"}')http.del(url: string, headers?: map): Task<HttpResponse>
Section titled “http.del(url: string, headers?: map): Task<HttpResponse>”Performs an asynchronous DELETE request. An optional headers map can be passed as the second argument.
const resp = await http.del("https://api.example.com/users/1")println(resp.status) // 204http.patch(url: string, body: string, contentType?: string): Task<HttpResponse>
Section titled “http.patch(url: string, body: string, contentType?: string): Task<HttpResponse>”Performs an asynchronous PATCH request.
const resp = await http.patch( "https://api.example.com/users/1", '{"name": "Charlie"}')http.request(method: string, url: string, body?: string, headers?: map): Task<HttpResponse>
Section titled “http.request(method: string, url: string, body?: string, headers?: map): Task<HttpResponse>”Performs a custom HTTP request with any method.
const resp = await http.request("OPTIONS", "https://api.example.com/users")Response Type
Section titled “Response Type”All HTTP functions return a Task<HttpResponse>. Use await to get the response.
dataType HttpResponse { status: int body: string headers: any}| Field | Type | Description |
|---|---|---|
status | int | HTTP status code (200, 404, etc.) |
body | string | Response body as a string |
headers | any | Response headers |
Function Reference
Section titled “Function Reference”| Function | Description |
|---|---|
http.get(url, headers?) | HTTP GET request |
http.post(url, body, contentType?) | HTTP POST request |
http.put(url, body, contentType?) | HTTP PUT request |
http.del(url, headers?) | HTTP DELETE request |
http.patch(url, body, contentType?) | HTTP PATCH request |
http.request(method, url, body?, headers?) | Custom HTTP request |
Example: Fetching and Parsing JSON
Section titled “Example: Fetching and Parsing JSON”import { http } from "std/http"import { json } from "std/json"
async function fetchUser(id: int): any { const resp = await http.get("https://api.example.com/users/" + id) if (resp.status == 200) { return json.parse(resp.body) } throw new Error("Failed to fetch user: " + resp.status)}
const user = await fetchUser(1)println(user["name"])