zen

package module
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 30 Imported by: 0

README

Zen

Go Reference

A lightweight, high-performance HTTP microframework for Go built on net/http. Zero-allocation radix tree routing, batteries-included middleware, and a minimal API.

Features

  • Radix tree router - per-method radix tree with zero-alloc path params, 405 detection, trailing-slash redirect
  • Request binding - bind JSON, XML, form, query, headers, and path params via struct tags
  • Pluggable validation - go-playground/validator integration with optional auto-validation
  • OpenAPI generation - auto-generated 3.0.3 spec + Swagger UI, zero cost when unused
  • Auth - JWT, Basic, API Key, Session, OAuth2, OIDC with RBAC/PBAC (separate auth package)
  • 8 built-in middleware - Recover, Logger, CORS, CSRF, Compress, Rate Limit, Body Limit, Pprof
  • Structured logger - colored output, slog levels (FATAL/ERROR/WARN/INFO/DEBUG/TRACE), NO_COLOR support
  • Zero external router dependencies - pure net/http + slog

Installation

go get github.com/Pavan-Silva/go-zen

Quick Start

package main

import (
    "github.com/Pavan-Silva/go-zen"
    "github.com/Pavan-Silva/go-zen/middleware"
)

func main() {
    r := zen.New(":8080")
    r.Use(middleware.Recover, middleware.Logger)

    r.GET("/hello", func(c *zen.Ctx) {
        c.String(200, "Hello, World!")
    })

    r.GET("/users/:id", func(c *zen.Ctx) {
        id := c.Param("id")
        c.JSON(200, map[string]string{"id": id})
    })

    r.Run()
}

Documentation

Full docs at zen-docs-steel.vercel.app.

License

MIT

Documentation

Overview

Package zen provides binding of HTTP request data into Go structs and maps.

Subsystem overview

The binding subsystem maps incoming data from four sources onto a destination:

  • Path parameters (via BindPathValues)
  • Query parameters (via BindQueryParams)
  • Request body (via BindBody)
  • HTTP headers (via BindHeaders)

Tag resolution order

For a given source each struct field is located by looking up its struct tag (param / query / form / header). If that tag is empty the json tag is tried next. If the json tag is also empty (or set to "-") the field name is used as-is. This allows a single set of json tags to double as binding tags in most cases.

Supported field types

Basic types (int*, uint*, float*, bool, string), pointers to those types, slices of those types, time.Time (with format tag), BindUnmarshaler, encoding.TextUnmarshaler, and multipart.FileHeader variants.

Package zen is a lightweight, high-performance HTTP microframework built on net/http with a custom radix tree router.

Quick Start

r := zen.New(":8080")
r.GET("/hello", func(c *zen.Ctx) {
    c.String(200, "Hello, World!")
})
r.Run()

Middleware

Zen supports both global and per-route middleware:

r.Use(middleware.Recover)
r.Use(middleware.Logger)

Routing

Routes use Go 1.22+ patterns with path parameters:

r.GET("/users/{id}", getUser)
r.POST("/users", createUser)
r.PUT("/users/{id}", updateUser)
r.DELETE("/users/{id}", deleteUser)

Route Groups

api := r.Group("/api")
api.HandleRaw("GET /health", healthCheck)

Binding and Validation

var req CreateUserRequest
if err := c.BindJSON(&req); err != nil {
    c.Error(400, "invalid request")
    return
}
if err := c.Validate(&req); err != nil {
    c.Error(400, err.Error())
    return
}

Context and Lifecycle

A zen.Ctx is created per request via sync.Pool and released back after the request completes. The hot path avoids context.WithValue entirely; FromRequest is only needed for interop with standard http.Handler patterns.

Performance

Zen is designed for zero-allocation middleware chains, pooled Ctx and streaming JSON/XML encoding.

Index

Constants

View Source
const HeaderXRequestID = "X-Request-ID"

HeaderXRequestID is the canonical header name for request IDs. Set on responses by the Request ID middleware.

Variables

View Source
var ErrFlusherUnsupported = errors.New("sse: SSE requires http.Flusher")

ErrFlusherUnsupported is returned by SSEvent when the ResponseWriter does not implement http.Flusher.

View Source
var ErrInvalidBindTarget = errors.New("http: bind dest must be a pointer to a struct or map")

ErrInvalidBindTarget is returned when the bind destination is not a pointer to a struct or map.

Functions

func BindBody added in v1.4.0

func BindBody(c *Ctx, dest any) error

BindBody binds the request body to dest based on the Content-Type header. Supported content types:

  • application/json
  • application/xml, text/xml
  • application/x-www-form-urlencoded
  • multipart/form-data
  • any type ending with +json or /json

func BindHeaders added in v1.4.0

func BindHeaders(c *Ctx, dest any) error

BindHeaders binds HTTP request headers to dest. Headers are mapped onto struct fields tagged with the "header" struct tag. Header names are matched case-insensitively.

func BindPathValues added in v1.4.0

func BindPathValues(c *Ctx, dest any) error

BindPathValues binds URL path parameters to dest. Path params are extracted from the route pattern and mapped onto struct fields tagged with the "param" struct tag.

func BindQueryParams added in v1.4.0

func BindQueryParams(c *Ctx, dest any) error

BindQueryParams binds query parameters to dest. Query params are mapped onto struct fields tagged with the "query" struct tag.

func RenderWriter added in v1.4.0

func RenderWriter(w io.Writer, tmpl *Templates, name string, data any) error

RenderWriter executes a named template and writes to an io.Writer. Useful for testing or composing templates.

Example:

var buf strings.Builder
zen.RenderWriter(&buf, t, "index.html", data)

Types

type BindMultipleUnmarshaler added in v1.4.0

type BindMultipleUnmarshaler interface {
	UnmarshalParams(params []string) error
}

BindMultipleUnmarshaler is the interface implemented by types that can deserialize a slice of string values. When a struct field implements this interface the entire set of values for the matching form key is passed at once rather than being iterated element by element.

type BindUnmarshaler added in v1.4.0

type BindUnmarshaler interface {
	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method. Types implementing this interface gain control over how a single string value is deserialised during binding.

type Config added in v1.2.0

type Config struct {
	ReadTimeout       time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	ReadHeaderTimeout time.Duration
	MaxHeaderBytes    int
	ShutdownTimeout   time.Duration
}

Config holds server-level timeout and header size settings. Use DefaultConfig to obtain sensible defaults, then override fields as needed.

func DefaultConfig added in v1.2.0

func DefaultConfig() Config

DefaultConfig returns a Config with standard timeout and buffer values. Timeouts and MaxHeaderBytes default to 0 to bypass the Go standard library's tracking loops, matching raw net/http performance baselines.

type Ctx added in v1.2.0

type Ctx struct {
	Response http.ResponseWriter
	Request  *http.Request
	// contains filtered or unexported fields
}

Ctx is the per-request context container for zen handlers and middleware components. Valid ONLY for the explicit lifetime of the request—never preserve references beyond handler returns.

func FromContext added in v1.2.0

func FromContext(ctx context.Context) (*Ctx, bool)

FromContext extracts a Ctx from a context.Context.

func FromRequest

func FromRequest(r *http.Request) (*Ctx, bool)

FromRequest extracts a Ctx from an http.Request.

func (*Ctx) Attachment added in v1.2.0

func (c *Ctx) Attachment(filePath, attachmentName string)

Attachment sends the requested file as a downloadable attachment. The Content-Disposition header is set with the provided attachment name. If attachmentName is empty, the file base name is used.

Example:

c.Attachment("/tmp/report.pdf", "monthly-report.pdf")

func (*Ctx) Bind added in v1.2.0

func (c *Ctx) Bind(dest any) error

Bind binds path params, query params (GET/DELETE/HEAD), and the request body to dest. The order of precedence is:

  1. Path parameters
  2. Query parameters (only for GET, DELETE, HEAD)
  3. Request body (Content-Type driven)

func (*Ctx) BindForm added in v1.2.0

func (c *Ctx) BindForm(dest any) error

BindForm binds form data from the request body to dest. It parses the request body as application/x-www-form-urlencoded (or multipart form data that was already parsed) and maps values onto struct fields tagged with the "form" struct tag.

func (*Ctx) BindJSON added in v1.2.0

func (c *Ctx) BindJSON(dest any) error

BindJSON decodes the request body as JSON into dest.

func (*Ctx) BindXML added in v1.2.0

func (c *Ctx) BindXML(dest any) error

BindXML decodes the request body as XML into dest.

func (*Ctx) Blob added in v1.2.0

func (c *Ctx) Blob(status int, contentType string, data []byte)

Blob writes a byte slice as the response body with the given content type. The response Content-Type is set to the provided MIME type.

Example:

data := []byte("id,name\n1,John Doe")
c.Blob(http.StatusOK, "text/csv", data)

func (*Ctx) Body added in v1.2.0

func (c *Ctx) Body() ([]byte, error)

Body reads and returns the complete raw request body as a byte slice. It is the caller's responsibility to interpret the bytes.

func (*Ctx) ClientIP added in v1.4.0

func (c *Ctx) ClientIP() string

ClientIP returns the client's IP address by checking X-Forwarded-For and X-Real-IP headers before falling back to the remote address.

func (*Ctx) ContentType added in v1.4.0

func (c *Ctx) ContentType() string

ContentType returns the MIME content type of the request body, stripped of any parameters (e.g. "application/json", "text/html; charset=utf-8" → "text/html").

func (*Ctx) Copy added in v1.2.0

func (c *Ctx) Copy() *Ctx

Copy returns a new Ctx with a deep copy of the store.

func (*Ctx) DefaultParam added in v1.4.0

func (c *Ctx) DefaultParam(key, defaultVal string) string

DefaultParam returns the path parameter value for the given key, falling back to the provided default value if the parameter is missing or empty.

Example:

c.DefaultParam("id", "default")  // GET /users/42 -> "42"
c.DefaultParam("id", "default")  // GET /users -> "default"

func (*Ctx) DefaultQuery added in v1.4.0

func (c *Ctx) DefaultQuery(key, defaultVal string) string

DefaultQuery returns the query parameter value for the given key, falling back to the provided default value if the parameter is missing or empty.

Example:

c.DefaultQuery("page", "1")  // GET /items?page=3 -> "3"
c.DefaultQuery("page", "1")  // GET /items -> "1"

func (*Ctx) Error added in v1.2.0

func (c *Ctx) Error(status int, message string)

Error writes a plain text error message to the response with the given HTTP status. Unlike JSON(), this sends plain text without JSON encoding, similar to http.Error(). The response Content-Type header is set to "text/plain; charset=utf-8".

This is the preferred method for simple error responses where JSON structure is not needed. For structured error responses, use JSON() with a plain map or custom struct.

Example:

c.Error(http.StatusBadRequest, "invalid email format")

func (*Ctx) File added in v1.2.0

func (c *Ctx) File(filePath string)

File sends the requested file as the HTTP response body. The content type is inferred automatically and errors are handled by http.ServeFile.

Example:

c.File("/tmp/report.pdf")

func (*Ctx) FormFile added in v1.2.0

func (c *Ctx) FormFile(fieldName string) (*multipart.FileHeader, multipart.File, error)

FormFile retrieves a single file from a multipart form upload. Returns the file header and a file handle for streaming. The caller is responsible for closing the file.

Example:

header, file, err := c.FormFile("avatar")
if err != nil {
    c.Error(http.StatusBadRequest, err.Error())
    return
}
defer file.Close()

func (*Ctx) FormFiles added in v1.2.0

func (c *Ctx) FormFiles(fieldName string) ([]*multipart.FileHeader, error)

FormFiles retrieves all file headers for a multipart form field. The caller opens each file individually for streaming access.

Example:

headers, err := c.FormFiles("attachments")
if err != nil {
    c.Error(http.StatusBadRequest, err.Error())
    return
}
for _, h := range headers {
    file, _ := h.Open()
    defer file.Close()
}

func (*Ctx) Get added in v1.2.0

func (c *Ctx) Get(key string) (any, bool)

Get retrieves a value from the context store.

func (*Ctx) HTML added in v1.2.0

func (c *Ctx) HTML(status int, html string)

HTML writes an HTML string directly to the response with the given HTTP status. The response Content-Type header is automatically set to "text/html; charset=utf-8".

Example:

c.HTML(http.StatusOK, "<h1>Hello World</h1>")

func (*Ctx) Header added in v1.2.0

func (c *Ctx) Header(key string) string

Header returns the value of a request header by key. Returns an empty string if the header is not present.

Example:

token := c.Header("Authorization")  // "Bearer <token>"

func (*Ctx) Inline added in v1.2.0

func (c *Ctx) Inline(filePath string)

Inline sends the requested file to be displayed inline by the browser. The Content-Disposition header is set to inline.

Example:

c.Inline("/tmp/image.png")

func (*Ctx) IsAjax added in v1.4.0

func (c *Ctx) IsAjax() bool

IsAjax returns true if the request was made via XMLHttpRequest (X-Requested-With header).

func (*Ctx) JSON added in v1.2.0

func (c *Ctx) JSON(status int, data any)

JSON encodes data as JSON and streams it straight to the response writer.

func (*Ctx) JSONPretty added in v1.4.0

func (c *Ctx) JSONPretty(status int, data any)

JSONPretty encodes data as indented JSON for human-readable responses.

func (*Ctx) Keys added in v1.2.0

func (c *Ctx) Keys() map[string]any

Keys returns a copy of all key-value entries in the store.

func (*Ctx) Next added in v1.2.0

func (c *Ctx) Next()

Next calls the next handler in the chain.

func (*Ctx) Param added in v1.2.0

func (c *Ctx) Param(key string) string

Param returns the URL path parameter for the given key.

Given a route registered as "GET /users/{id}", the handler can retrieve the captured segment with:

id := c.Param("id")  // GET /users/42 -> "42"

func (*Ctx) Params added in v1.4.0

func (c *Ctx) Params() map[string]string

Params returns all matched URL path parameters as a map.

func (*Ctx) QueryParam added in v1.2.0

func (c *Ctx) QueryParam(key string) string

QueryParam returns the first value of a query parameter from the request URL. Returns an empty string if the parameter is not present.

Example:

page := c.QueryParam("page")      // GET /posts?page=2 -> "2"
search := c.QueryParam("q")       // GET /posts?q=golang-> "golang"

func (*Ctx) QueryParams added in v1.4.0

func (c *Ctx) QueryParams() map[string][]string

QueryParams returns all query parameters from the request URL as a map. Each key maps to a slice of values (e.g. ?a=1&a=2 -> {"a": ["1", "2"]}).

func (*Ctx) ReadFile added in v1.2.0

func (c *Ctx) ReadFile(fieldName string) (header *multipart.FileHeader, content []byte, err error)

ReadFile is a convenience method that reads a single uploaded file into memory. For large files, use FormFile() and stream the content instead.

func (*Ctx) Redirect added in v1.2.0

func (c *Ctx) Redirect(status int, location string)

Redirect sends an HTTP redirect to the specified location. It sets the Location header and writes the provided redirect status.

Example:

c.Redirect(http.StatusMovedPermanently, "https://example.com/new")

func (*Ctx) Render added in v1.4.0

func (c *Ctx) Render(status int, tmpl *Templates, name string, data any)

Render executes a named template and writes the result to the response. Sets Content-Type to "text/html; charset=utf-8".

Write errors are logged but not returned (they indicate connection issues).

Example:

c.Render(http.StatusOK, t, "index.html", map[string]any{"title": "Home"})

func (*Ctx) SSEvent added in v1.2.0

func (c *Ctx) SSEvent(event string, data any) error

SSEvent writes a Server-Sent Event to the client. It sets required SSE headers and flushes the response.

func (*Ctx) Set added in v1.2.0

func (c *Ctx) Set(key string, val any)

Set stores a value in the context. The internal map is allocated on first use.

func (*Ctx) Status added in v1.2.0

func (c *Ctx) Status(status int)

Status writes a response header with no-body and the given HTTP status.

Example:

c.Status(http.StatusNoContent)

func (*Ctx) Stream added in v1.2.0

func (c *Ctx) Stream(status int, contentType string, body io.Reader) error

Stream copies data from an io.Reader to the response body with the given content type. The response Content-Type is set to the provided MIME type.

Example:

f, err := os.Open("/tmp/image.png")
if err != nil {
    return err
}
defer f.Close()
return c.Stream(http.StatusOK, "image/png", f)

func (*Ctx) String added in v1.2.0

func (c *Ctx) String(status int, text string)

String writes a plain text string directly to the response with the given HTTP status.

Example:

c.String(http.StatusOK, "Hello World")

func (*Ctx) Validate added in v1.4.0

func (c *Ctx) Validate(dest any) error

Validate runs struct validation on dest using the engine's configured validator. Returns nil if no validator is set (validation is opt-in).

func (*Ctx) XML added in v1.2.0

func (c *Ctx) XML(status int, data any)

XML encodes data as XML and writes it to the response with the given HTTP status code.

type Engine added in v1.2.0

type Engine struct {
	RouterGroup

	JSONSerializer     JSONSerializer
	XMLSerializer      XMLSerializer
	MaxMultipartMemory int64
	// contains filtered or unexported fields
}

Engine is the top-level application container. It embeds a root RouterGroup and owns the radix tree router and the http.Server.

func New

func New(addr string, config ...Config) *Engine

New creates an Engine with the given listen address and optional custom Config.

func (*Engine) DefaultValidator added in v1.4.0

func (e *Engine) DefaultValidator() *validator.Validate

DefaultValidator returns the underlying go-playground/validator/v10 instance when using the default built-in validator, or nil if a custom validator is set. Use this to register custom validation tags:

e.DefaultValidator().RegisterValidation("is-even", func(fl validator.FieldLevel) bool {
    return fl.Field().Int()%2 == 0
})

func (*Engine) EnableAutoValidation added in v1.4.0

func (e *Engine) EnableAutoValidation()

EnableAutoValidation enables automatic Validate() calls after BindJSON, BindXML, and BindForm for this engine.

func (*Engine) File added in v1.2.0

func (e *Engine) File(pattern, filePath string)

File serves a single file at the given path pattern via http.ServeFile.

func (*Engine) NoMethod added in v1.4.0

func (e *Engine) NoMethod(handlers ...HandlerFunc)

NoMethod registers handlers that run when a path matches but the request method does not. They replace the default 405 response and run after the root middleware chain. The Allow header is set before they run.

func (*Engine) NoRoute added in v1.4.0

func (e *Engine) NoRoute(handlers ...HandlerFunc)

NoRoute registers handlers that run when no route matches the request. They replace the default 404 response and run after the root middleware chain. Handlers are responsible for writing the response.

func (*Engine) Run added in v1.2.0

func (e *Engine) Run()

Run starts the HTTP server and blocks until a shutdown signal is received.

func (*Engine) RunTLS added in v1.2.0

func (e *Engine) RunTLS(certFile, keyFile string)

RunTLS starts the HTTPS server with the given certificate and key files, and blocks until a shutdown signal is received.

func (*Engine) ServeHTTP added in v1.2.0

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface using the radix tree router.

func (*Engine) SetValidator added in v1.4.0

func (e *Engine) SetValidator(v Validator)

SetValidator sets a custom validator for request validation on this engine. Pass nil to disable validation entirely.

func (*Engine) Static added in v1.2.0

func (e *Engine) Static(prefix, root string)

Static serves static files from the given OS directory under the specified path prefix.

func (*Engine) StaticFS added in v1.2.0

func (e *Engine) StaticFS(prefix string, filesystem fs.FS)

StaticFS serves static files from any fs.FS under the specified path prefix.

func (*Engine) Validate added in v1.4.0

func (e *Engine) Validate(dest any) error

Validate runs struct validation on dest using the engine's configured validator. Returns nil if no validator is set (validation is opt-in).

type FormError

type FormError struct {
	Field string
	Err   error
}

FormError represents a form binding error for a specific field.

func (*FormError) Error

func (e *FormError) Error() string

func (*FormError) Unwrap

func (e *FormError) Unwrap() error

type HandlerFunc added in v1.2.0

type HandlerFunc func(*Ctx)

HandlerFunc is the universal type for both route handlers and middleware.

type JSONSerializer added in v1.4.0

type JSONSerializer interface {
	Serialize(c *Ctx, v any, indent string) error
	Deserialize(c *Ctx, v any) error
}

JSONSerializer is the interface for JSON encoding and decoding. Implementations handle serializing Go values to JSON for responses and deserializing JSON request bodies into Go values.

type RouterGroup added in v1.2.0

type RouterGroup struct {
	// contains filtered or unexported fields
}

RouterGroup groups routes under a common prefix with optional shared middleware. An Engine embeds a root RouterGroup; Group creates child groups.

func (*RouterGroup) DELETE added in v1.2.0

func (g *RouterGroup) DELETE(path string, handlers ...HandlerFunc)

DELETE registers a handler for the DELETE method.

func (*RouterGroup) GET added in v1.2.0

func (g *RouterGroup) GET(path string, handlers ...HandlerFunc)

GET registers a handler for the GET method. The final element in handlers is the main handler; preceding elements are middleware.

func (*RouterGroup) Group added in v1.2.0

func (g *RouterGroup) Group(prefix string, middleware ...HandlerFunc) *RouterGroup

Group creates a child group with an additional path prefix and optional middleware. The child group inherits all parent middleware and appends the new middleware after it. Uses a single upfront allocation to prevent double-allocation slice resizes.

func (*RouterGroup) HEAD added in v1.2.0

func (g *RouterGroup) HEAD(path string, handlers ...HandlerFunc)

HEAD registers a handler for the HEAD method.

func (*RouterGroup) HandleRaw added in v1.2.0

func (g *RouterGroup) HandleRaw(pattern string, handler http.Handler)

HandleRaw registers a raw http.Handler on the router using the zen handler chain. The pattern uses Go 1.22+ ServeMux syntax ({param}, {path...}) which is automatically converted to the router's native syntax (:param, *path). The group prefix is prepended to the path automatically.

The raw handler can recover the current Ctx from the request with FromRequest (and must not retain it beyond the request lifetime).

func (*RouterGroup) OPTIONS added in v1.2.0

func (g *RouterGroup) OPTIONS(path string, handlers ...HandlerFunc)

OPTIONS registers a handler for the OPTIONS method.

func (*RouterGroup) PATCH added in v1.2.0

func (g *RouterGroup) PATCH(path string, handlers ...HandlerFunc)

PATCH registers a handler for the PATCH method.

func (*RouterGroup) POST added in v1.2.0

func (g *RouterGroup) POST(path string, handlers ...HandlerFunc)

POST registers a handler for the POST method.

func (*RouterGroup) PUT added in v1.2.0

func (g *RouterGroup) PUT(path string, handlers ...HandlerFunc)

PUT registers a handler for the PUT method.

func (*RouterGroup) Prefix added in v1.2.0

func (g *RouterGroup) Prefix() string

Prefix returns the full path prefix of this group.

func (*RouterGroup) Use added in v1.2.0

func (g *RouterGroup) Use(middleware ...HandlerFunc)

Use appends middleware to the group. Middleware runs for every route registered on this group.

type SkipFunc added in v1.2.0

type SkipFunc func(*http.Request) bool

SkipFunc decides whether a request should bypass middleware (auth, body limit, etc). It receives the current request and returns true for routes to skip.

type Templates added in v1.4.0

type Templates struct {
	// contains filtered or unexported fields
}

Templates holds parsed HTML templates for rendering.

func LoadTemplates added in v1.4.0

func LoadTemplates(fsys fs.FS, pattern string) (*Templates, error)

LoadTemplates parses all templates matching the glob pattern from the given filesystem. Use os.DirFS for the local filesystem or embed.FS for embedded templates.

Example:

t := zen.LoadTemplates(os.DirFS("views"), "*.html")
r.GET("/", func(c *zen.Ctx) {
    c.Render(200, t, "index.html", map[string]any{"title": "Home"})
})

type TestRequest added in v1.4.0

type TestRequest struct {
	Request  *http.Request
	Response *httptest.ResponseRecorder
}

TestRequest bundles a request and response recorder for convenient testing.

func NewTestRequest added in v1.4.0

func NewTestRequest(method, path string, body io.Reader) *TestRequest

NewTestRequest creates a TestRequest with the given method, path, and optional body.

Example:

tr := zen.NewTestRequest("GET", "/api/users", nil)
r.ServeHTTP(tr.Response, tr.Request)
fmt.Println(tr.Response.Code)

func NewTestRequestWithJSON added in v1.4.0

func NewTestRequestWithJSON(method, path, jsonBody string) *TestRequest

NewTestRequestWithJSON creates a test request with a JSON string body and sets the Content-Type header to application/json.

Example:

tr := zen.NewTestRequestWithJSON("POST", "/api/users", `{"name":"John"}`)
r.ServeHTTP(tr.Response, tr.Request)

func (*TestRequest) Serve added in v1.4.0

func (tr *TestRequest) Serve(r *Engine)

Serve calls Engine.ServeHTTP with the test request.

type Validator added in v1.2.0

type Validator interface {
	Validate(i any) error
}

Validator is the interface for request validation. Implement this to plug in any validation library.

Example:

type CustomValidator struct {
    validator *validator.Validate
}

func (cv *CustomValidator) Validate(i any) error {
    return cv.validator.Struct(i)
}

type ValidatorFunc added in v1.4.0

type ValidatorFunc func(i any) error

ValidatorFunc is a helper type to turn a plain function into a Validator.

func (ValidatorFunc) Validate added in v1.4.0

func (f ValidatorFunc) Validate(i any) error

Validate implements the Validator interface for ValidatorFunc.

type XMLSerializer added in v1.4.0

type XMLSerializer interface {
	Serialize(c *Ctx, v any) error
	Deserialize(c *Ctx, v any) error
}

XMLSerializer is the interface for XML encoding and decoding. Implementations handle serializing Go values to XML for responses and deserializing XML request bodies into Go values.

Directories

Path Synopsis
Package auth provides authentication and authorization middleware (JWT, OAuth2, OIDC, Basic, RBAC, ABAC, PBAC, session).
Package auth provides authentication and authorization middleware (JWT, OAuth2, OIDC, Basic, RBAC, ABAC, PBAC, session).
Package env provides helpers for reading configuration from environment variables.
Package env provides helpers for reading configuration from environment variables.
internal
log
system
Package system provides build-time metadata (version, banner) for the zen framework.
Package system provides build-time metadata (version, banner) for the zen framework.
Package middleware provides built-in HTTP middleware for zen (recovery, logging, CORS, CSRF, compression, rate limiting, body limit, pprof).
Package middleware provides built-in HTTP middleware for zen (recovery, logging, CORS, CSRF, compression, rate limiting, body limit, pprof).
Package openapi generates OpenAPI 3.0.3 specifications and serves the Swagger UI for zen routes.
Package openapi generates OpenAPI 3.0.3 specifications and serves the Swagger UI for zen routes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL