HTTP Context

Every Nimbus handler receives a *http.Context — a single object that wraps the HTTP request, response writer, and route parameters. It provides convenience methods so you rarely need to interact with the raw net/http types directly.

The Context Struct

The context.Context struct is defined in the github.com/CodeSyncr/nimbus/context package:

type Context struct {
    Request  *http.Request
    Response http.ResponseWriter
    Params   map[string]string
}
  • Request — the standard *http.Request with headers, body, URL, method, and more.
  • Response — the standard http.ResponseWriter for writing the response.
  • Params — a map of route parameters extracted from the URL path.

Param(name string) string

Returns the value of a named route parameter. Parameters are defined with :name in the route path.

// Route: /users/:id
app.Router.Get("/users/:id", func(c *http.Context) error {
    id := c.Param("id") // "42" for /users/42
    return c.JSON(200, map[string]string{"id": id})
})

JSON(code int, body any) error

Sends a JSON response. Sets Content-Type: application/json, writes the status code, and encodes the body as JSON.

return c.JSON(200, map[string]any{
    "users": users,
    "total": len(users),
})

String(code int, s string)

Sends a plain text response with Content-Type: text/plain.

c.String(200, "OK")

View(name string, data any) error

Renders a .nimbus template and sends HTML. The name is the template path relative to views/ (without the .nimbus extension). The data map provides variables to the template.

return c.View("posts/show", map[string]any{
    "title": post.Title,
    "post":  post,
})

Redirect(code int, url string)

Sends an HTTP redirect. Common status codes are 301 (permanent), 302 (temporary), and 303 (see other, used after POST).

c.Redirect(302, "/login")
c.Redirect(301, "/new-url")

Status(code int) *Context

Sets the HTTP status code and returns the context for chaining. Useful when you want to set a status before writing the response body manually.

c.Status(204) // No Content

Request Body & Query Binding

Nimbus provides first-party typed binding methods for JSON payloads, URL queries, and form data:

// Bind JSON request body
var req CreateUserRequest
if err := c.BindJSON(&req); err != nil {
    return c.JSON(400, map[string]string{"error": "invalid json payload"})
}

// Bind URL query parameters into struct
var filter ProductFilter
if err := c.BindQuery(&filter); err != nil {
    return err
}

// Bind Form POST (urlencoded or multipart)
var form ContactForm
if err := c.BindForm(&form); err != nil {
    return err
}

File Uploads: File & SaveUploadedFile

Easily extract and save multipart uploaded files directly to disk:

file, fh, err := c.File("avatar")
if err != nil {
    return c.JSON(400, map[string]string{"error": "avatar file is required"})
}

// Save directly to storage path
if err := c.SaveUploadedFile(fh, "storage/avatars/" + fh.Filename); err != nil {
    return err
}

Validation Errors Response: ValidationErrors

Returns a standard 422 Unprocessable Entity response containing validation error messages:

if err := validation.ValidateStruct(&req); err != nil {
    return c.ValidationErrors(err)
}

Server-Sent Events (SSE): SSEStream

Stream live events to clients with automatic headers, formatting, and flushing:

app.Router.Get("/stream", func(c *http.Context) error {
    return c.SSEStream(func(w *http.SSEWriter) error {
        for i := 1; i <= 5; i++ {
            _ = w.Event("counter", map[string]int{"count": i})
            time.Sleep(1 * time.Second)
        }
        return nil
    })
})

Accessing Request and Response Directly

For lower-level control, access the underlying request and response objects:

// Read a request header
auth := c.Request.Header.Get("Authorization")

// Set a response header
c.Response.Header().Set("X-Request-Id", requestID)

// Get the HTTP method
method := c.Request.Method

// Get the full URL
url := c.Request.URL.String()

Handler Signature

All Nimbus handlers follow the same signature. The returned error, if non-nil, results in a 500 Internal Server Error (unless the Recover middleware handles it).

type HandlerFunc func(*http.Context) error

This applies to inline handlers, controller methods, and middleware inner functions alike.