Request Object
Every handler receives a *Request containing parsed HTTP data:
type Request struct { Method string Path string Proto string Host string RemoteAddr string Headers [][2]string Body []byte StreamID uint32 IsH2 bool Params [8]Param ParamCount int StreamWriter StreamWriter }
| Field | Type | Description |
|---|---|---|
Method |
string |
HTTP method: "GET", "POST", etc. |
Path |
string |
Request path: "/users/42" |
Proto |
string |
Protocol: "HTTP/1.1" or "HTTP/2.0" |
Host |
string |
Request host: "example.com" |
RemoteAddr |
string |
Client IP address |
Headers |
[][2]string |
Header key-value pairs |
Body |
[]byte |
Request body bytes |
StreamID |
uint32 |
HTTP/2 stream ID |
IsH2 |
bool |
True if HTTP/2 request |
Params |
[8]Param |
Route parameters (zero-alloc, fixed-size) |
ParamCount |
int |
Number of params captured |
StreamWriter |
StreamWriter |
Stream writer for streamed responses; populated once acquired on the epoll backend |
Reading Headers
Use Header() for case-insensitive header lookup:
s.Router.GET("/info", func(req *core.Request, resp *core.Response) { contentType := req.Header("Content-Type") auth := req.Header("Authorization") userAgent := req.Header("User-Agent") for _, h := range req.Headers { key, val := h[0], h[1] fmt.Printf("%s: %s\n", key, val) } })
Route Parameters
Access named parameters from the URL path:
s.Router.GET("/users/:id/posts/:postId", func(req *core.Request, resp *core.Response) { userId := req.ParamValue("id") postId := req.ParamValue("postId") resp.String("User " + userId + ", Post " + postId) }) req.SetParam("key", "value")
Request Body
The body is available as raw bytes on req.Body:
s.Router.POST("/upload", func(req *core.Request, resp *core.Response) { body := req.Body if len(body) == 0 { resp.Status(400).String("Empty body") return } resp.Status(201).String("Received") })
Body size is enforced by MaxBodySize in the server config. Requests exceeding this limit are rejected before reaching your handler.
Cookies
Read cookies from the request and set cookies on the response:
Reading Cookies
| Method | Returns | Description |
|---|---|---|
req.Cookie(name) | string | Returns the value of the named cookie, or empty string if not found |
req.Cookies() | []Cookie | Returns all parsed cookies from the request |
Setting Cookies
| Method | Returns | Description |
|---|---|---|
resp.SetCookie(cookie) | *Response | Sets a Set-Cookie header on the response |
resp.DeleteCookie(name) | *Response | Deletes a cookie by setting MaxAge to -1 |
Cookie Struct
type Cookie struct { Name string Value string Path string Domain string MaxAge int Expires time.Time Secure bool HttpOnly bool SameSite SameSite }
SameSite Constants
| Constant | Description |
|---|---|
SameSiteDefault | Browser default behavior (typically Lax) |
SameSiteLax | Sent with top-level navigations and GET requests from third-party sites |
SameSiteStrict | Only sent in first-party context |
SameSiteNone | Sent in all contexts; requires Secure: true |
Example
s.Router.GET("/dashboard", func(req *core.Request, resp *core.Response) { session := req.Cookie("session_id") if session == "" { resp.Status(401).String("Not authenticated") return } resp.String("Welcome back") }) s.Router.POST("/login", func(req *core.Request, resp *core.Response) { resp.SetCookie(core.Cookie{ Name: "session_id", Value: "abc123", Path: "/", MaxAge: 86400, Secure: true, HttpOnly: true, SameSite: core.SameSiteLax, }).String("Logged in") }) s.Router.POST("/logout", func(req *core.Request, resp *core.Response) { resp.DeleteCookie("session_id").String("Logged out") })
Query Parameters
Parse and access URL query parameters:
| Method | Returns | Description |
|---|---|---|
req.QueryParam(key) | string | Returns the first value for the given key |
req.QueryParamAll(key) | []string | Returns all values for the given key |
req.QueryParams() | map[string][]string | Returns all query parameters as a map |
req.Query contains the raw query string. The QueryParam methods parse it lazily on first access and cache the result.
Example
s.Router.GET("/search", func(req *core.Request, resp *core.Response) { q := req.QueryParam("q") page := req.QueryParam("page") tags := req.QueryParamAll("tag") all := req.QueryParams() resp.JSONMarshal(map[string]any{ "query": q, "page": page, "tags": tags, "params": all, }) })
Form Data & File Uploads
Parse URL-encoded form bodies and multipart file uploads:
| Method | Returns | Description |
|---|---|---|
req.FormValue(key) | string | Parses application/x-www-form-urlencoded body and returns the value for the given key |
req.FormFile(field) | (FileHeader, bool) | Parses multipart/form-data and returns the file for the given field name |
FileHeader Struct
type FileHeader struct { Filename string Size int64 ContentType string Data []byte }
Form Submission
s.Router.POST("/contact", func(req *core.Request, resp *core.Response) { name := req.FormValue("name") email := req.FormValue("email") message := req.FormValue("message") if name == "" || email == "" { resp.Status(400).String("Name and email are required") return } resp.Status(200).String("Thanks, " + name) })
File Upload
s.Router.POST("/upload", func(req *core.Request, resp *core.Response) { file, ok := req.FormFile("avatar") if !ok { resp.Status(400).String("No file uploaded") return } resp.JSONMarshal(map[string]any{ "filename": file.Filename, "size": file.Size, "type": file.ContentType, }) })
JSON Binding
Unmarshal the request body into a Go struct using Sonic:
| Method | Returns | Description |
|---|---|---|
req.BindJSON(v any) | error | Deserializes the request body JSON into the given value |
type CreateUserReq struct { Name string `json:"name"` Email string `json:"email"` Age int `json:"age"` } s.Router.POST("/users", func(req *core.Request, resp *core.Response) { var input CreateUserReq if err := req.BindJSON(&input); err != nil { resp.Status(400).JSONMarshal(map[string]string{ "error": err.Error(), }) return } resp.Status(201).JSONMarshal(map[string]any{ "created": input.Name, }) })
Per-Request Store
Attach arbitrary data to a request for sharing between middleware and handlers:
| Method | Returns | Description |
|---|---|---|
req.Set(key, value) | Store a value in the request context | |
req.Get(key) | (any, bool) | Retrieve a value; the bool indicates whether the key exists |
req.GetString(key) | string | Retrieve a value as a string; returns empty string if not found or not a string |
The per-request store is commonly used by middleware to pass data such as JWT claims, session info, or user IDs to downstream handlers.
Example
authMiddleware := func(req *core.Request, resp *core.Response) bool { token := req.Header("Authorization") userID := validateToken(token) if userID == "" { resp.Status(401).String("Unauthorized") return false } req.Set("user_id", userID) return true } s.Router.GET("/profile", func(req *core.Request, resp *core.Response) { userID := req.GetString("user_id") resp.JSONMarshal(map[string]string{ "user_id": userID, }) }, authMiddleware)
Response Object
The *Response provides a fluent API for building HTTP responses. Methods are chainable:
resp.Status(201). SetHeader("X-Custom", "value"). JSON([]byte(`{"created":true}`))
Status Codes
Set HTTP status code. Defaults to 200 if not set:
resp.Status(200) resp.Status(201) resp.Status(204) resp.Status(301) resp.Status(400) resp.Status(401) resp.Status(404) resp.Status(500)
Response Body
Multiple methods for setting the response body:
| Method | Content-Type | Description |
|---|---|---|
String(s) | text/plain | Plain text response |
HTML(s) | text/html | HTML response |
Bytes(b) | inherited | Raw byte response |
JSON(b) | application/json | Pre-serialized JSON bytes |
JSONString(s) | application/json | JSON from string |
JSONMarshal(v) | application/json | Marshal any value to JSON |
resp.String("Hello!") resp.HTML("<h1>Welcome</h1>") resp.JSON([]byte(`{"status":"ok"}`)) type User struct { Name string `json:"name"` Age int `json:"age"` } resp.JSONMarshal(User{Name: "Alice", Age: 30})
JSON Responses
For high-performance JSON, use JSON() with pre-serialized bytes to avoid reflection. For convenience, JSONMarshal() handles encoding:
resp.JSON([]byte(`{"users":[],"total":0}`)) err := resp.JSONMarshal(map[string]any{ "users": users, "total": len(users), })
Pooled JSON
For high-performance JSON serialization, ALOS provides a pooled Sonic JSON encoder that handles acquisition, marshaling, and recycling automatically:
j := core.AcquireJSON() resp.Status(200).JSON(j.Marshal(map[string]any{ "name": "Alice", "age": 30, "active": true, "tags": []string{"admin", "user"}, })) j.Release()
You can also marshal structs directly:
type User struct { Name string `json:"name"` Age int `json:"age"` Active bool `json:"active"` Tags []string `json:"tags"` } j := core.AcquireJSON() resp.Status(200).JSON(j.Marshal(User{ Name: "Alice", Age: 30, Active: true, Tags: []string{"admin", "user"}, })) j.Release()
Pooled JSON Methods
| Method | Description |
|---|---|
AcquireJSON() | Get a pooled JSON encoder |
Marshal(v any) | Serialize any value to JSON bytes using Sonic |
Release() | Return the encoder to the pool for reuse |
Response Headers
Set custom headers on the response. Headers are chainable:
resp.SetHeader("X-Custom", "value"). SetHeader("Cache-Control", "no-cache"). SetHeader("X-Request-ID", requestId). Status(200). JSON(data)
Body Read/Write
Low-level body access for advanced use cases:
| Method | Description |
|---|---|
SetBody(b []byte) | Replace the response body with raw bytes |
GetBody() []byte | Get the current response body bytes |
BodyLen() int | Get the current body length |
s.Router.GET("/raw", func(req *core.Request, resp *core.Response) { resp.SetBody([]byte("raw bytes")) resp.ContentType = "application/octet-stream" }) s.Router.GET("/transform", func(req *core.Request, resp *core.Response) { resp.JSON([]byte(`{"data":"original"}`)) body := resp.GetBody() modified := bytes.Replace(body, []byte("original"), []byte("modified"), 1) resp.SetBody(modified) })
Redirects
Send an HTTP redirect response:
| Method | Returns | Description |
|---|---|---|
resp.Redirect(url, code) | *Response | Sends an HTTP redirect to the given URL with the specified status code |
If code is 0, it defaults to 302 (Found).
Common Redirect Codes
| Code | Name | Description |
|---|---|---|
301 | Moved Permanently | Permanent redirect; browsers cache this |
302 | Found | Temporary redirect; method may change to GET |
303 | See Other | Redirect with GET; used after POST form submission |
307 | Temporary Redirect | Temporary redirect; preserves HTTP method |
308 | Permanent Redirect | Permanent redirect; preserves HTTP method |
Example
s.Router.GET("/old-page", func(req *core.Request, resp *core.Response) { resp.Redirect("/new-page", 301) }) s.Router.GET("/admin", func(req *core.Request, resp *core.Response) { session := req.Cookie("session_id") if session == "" { resp.Redirect("/login", 302) return } resp.String("Admin panel") }) s.Router.POST("/submit", func(req *core.Request, resp *core.Response) { resp.Redirect("/thank-you", 303) })
SSE Helper
Server-Sent Events (SSE) provide a simple way to push real-time updates from server to client over HTTP:
| Method | Returns | Description |
|---|---|---|
resp.SSE() | *SSEWriter | Creates a Server-Sent Events writer and sets appropriate headers |
sse.Send(event, data) | error | Sends a named event with data |
sse.SendData(data) | error | Sends a data-only event (no event name) |
sse.SendID(id, event, data) | error | Sends an event with an ID for client-side reconnection tracking |
sse.Close() | error | Closes the SSE stream |
Multiline data is handled automatically. Each line of the data string is sent as a separate data: field per the SSE specification.
Example
s.Router.GET("/notifications", func(req *core.Request, resp *core.Response) { sse := resp.SSE() sse.Send("connected", "Stream started") for i := 1; i <= 5; i++ { data := fmt.Sprintf(`{"count":%d}`, i) sse.SendID(fmt.Sprintf("%d", i), "update", data) time.Sleep(time.Second) } sse.SendData("Done") sse.Close() })
Streaming
Use SetStreamer and Streamer() for streaming responses. When a streamer is set, the normal body is bypassed and the StreamWriter handles output directly:
Streamed responses and SendFile run on the custom epoll backend over both plain HTTP and TLS. Acquire the stream writer via resp.EnsureStreamWriter().
| Method | Description |
|---|---|
SetStreamer(sw StreamWriter) | Enable streaming mode with the given writer |
Streamer() StreamWriter | Get the current streamer |
IsStreamed() bool | Check if response is in streaming mode |
SendFile(path string, opts ...SendFileOption) | Serve a file with MIME detection and range support |
s.Router.GET("/stream", func(req *core.Request, resp *core.Response) { sw := req.StreamWriter sw.WriteHeader(200, nil, "text/event-stream") for i := 0; i < 5; i++ { sw.WriteChunk([]byte(fmt.Sprintf("data: %d\n\n", i))) sw.Flush() time.Sleep(time.Second) } sw.Close() })
Serve files with options:
s.Router.GET("/download", func(req *core.Request, resp *core.Response) { resp.SendFile("./files/report.pdf", core.WithAttachment("report.pdf"), core.WithRateLimit(100), ) })
See the Streaming & Files page for the full StreamWriter API and SendFile options.
Connection Hijack
Take over the raw TCP connection for custom protocols. Returns the underlying net.Conn:
HijackConn lets a handler take over the raw connection. It is supported on the custom epoll backend, which also powers hijack-based features such as WebSocket upgrade.
s.Router.GET("/hijack", func(req *core.Request, resp *core.Response) { conn := req.HijackConn() if conn == nil { resp.Status(500).String("hijack failed") return } defer conn.Close() conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello")) })
When using ALOS's custom TLS 1.3, HijackConn returns a wrapper that transparently handles AEAD encryption/decryption. You read and write plaintext; the wrapper handles record-layer framing.