Request & Response

Zero-allocation request parsing with fluent response building, Sonic JSON, and compatibility APIs for streaming, file serving, and hijack.

Request Object

Every handler receives a *Request containing parsed HTTP data:

go
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:

go
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:

go
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:

go
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

MethodReturnsDescription
req.Cookie(name)stringReturns the value of the named cookie, or empty string if not found
req.Cookies()[]CookieReturns all parsed cookies from the request

Setting Cookies

MethodReturnsDescription
resp.SetCookie(cookie)*ResponseSets a Set-Cookie header on the response
resp.DeleteCookie(name)*ResponseDeletes a cookie by setting MaxAge to -1

Cookie Struct

go
type Cookie struct {
    Name     string
    Value    string
    Path     string
    Domain   string
    MaxAge   int
    Expires  time.Time
    Secure   bool
    HttpOnly bool
    SameSite SameSite
}

SameSite Constants

ConstantDescription
SameSiteDefaultBrowser default behavior (typically Lax)
SameSiteLaxSent with top-level navigations and GET requests from third-party sites
SameSiteStrictOnly sent in first-party context
SameSiteNoneSent in all contexts; requires Secure: true

Example

go
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:

MethodReturnsDescription
req.QueryParam(key)stringReturns the first value for the given key
req.QueryParamAll(key)[]stringReturns all values for the given key
req.QueryParams()map[string][]stringReturns 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

go
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:

MethodReturnsDescription
req.FormValue(key)stringParses 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

go
type FileHeader struct {
    Filename    string
    Size        int64
    ContentType string
    Data        []byte
}

Form Submission

go
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

go
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:

MethodReturnsDescription
req.BindJSON(v any)errorDeserializes the request body JSON into the given value
go
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:

MethodReturnsDescription
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)stringRetrieve 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

go
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:

go
resp.Status(201).
    SetHeader("X-Custom", "value").
    JSON([]byte(`{"created":true}`))

Status Codes

Set HTTP status code. Defaults to 200 if not set:

go
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:

MethodContent-TypeDescription
String(s)text/plainPlain text response
HTML(s)text/htmlHTML response
Bytes(b)inheritedRaw byte response
JSON(b)application/jsonPre-serialized JSON bytes
JSONString(s)application/jsonJSON from string
JSONMarshal(v)application/jsonMarshal any value to JSON
go
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:

go
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:

go
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:

go
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

MethodDescription
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:

go
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:

MethodDescription
SetBody(b []byte)Replace the response body with raw bytes
GetBody() []byteGet the current response body bytes
BodyLen() intGet the current body length
go
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:

MethodReturnsDescription
resp.Redirect(url, code)*ResponseSends an HTTP redirect to the given URL with the specified status code

If code is 0, it defaults to 302 (Found).

Common Redirect Codes

CodeNameDescription
301Moved PermanentlyPermanent redirect; browsers cache this
302FoundTemporary redirect; method may change to GET
303See OtherRedirect with GET; used after POST form submission
307Temporary RedirectTemporary redirect; preserves HTTP method
308Permanent RedirectPermanent redirect; preserves HTTP method

Example

go
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:

MethodReturnsDescription
resp.SSE()*SSEWriterCreates a Server-Sent Events writer and sets appropriate headers
sse.Send(event, data)errorSends a named event with data
sse.SendData(data)errorSends a data-only event (no event name)
sse.SendID(id, event, data)errorSends an event with an ID for client-side reconnection tracking
sse.Close()errorCloses 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

go
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().

MethodDescription
SetStreamer(sw StreamWriter)Enable streaming mode with the given writer
Streamer() StreamWriterGet the current streamer
IsStreamed() boolCheck if response is in streaming mode
SendFile(path string, opts ...SendFileOption)Serve a file with MIME detection and range support
go
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:

go
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.

go
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.