web

package module
v0.1.38 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: MIT Imports: 28 Imported by: 0

README

Web.go The library for web

中文文档: README_CN.md

Performance First

This library is optimized around low-latency request handling, tight routing, and low-allocation parsing/writing paths.

Current benchmark snapshot on darwin/arm64 (Apple M2):

Benchmark Result Memory
BenchmarkServeHTTPStaticJSON 152.4 ns/op 16 B/op, 1 alloc/op
BenchmarkServeHTTPPathParamJSON 196.3 ns/op 24 B/op, 2 alloc/op
BenchmarkServeHTTPStaticJSONRawMessage 119.9 ns/op 40 B/op, 2 alloc/op
BenchmarkTryParseJSONBodyFast 1417.0 ns/op 5600 B/op, 20 alloc/op
BenchmarkPostBytes 38264.0 ns/op 6165 B/op, 74 alloc/op
BenchmarkDoReqWithClientRawBody 189.4 ns/op 328 B/op, 7 alloc/op
BenchmarkServeHTTPBinary 125.2 ns/op 40 B/op, 2 alloc/op
BenchmarkServeHTTPAvro 124.7 ns/op 40 B/op, 2 alloc/op
BenchmarkTreeGetValueParamPooled 14.2 ns/op 0 B/op, 0 alloc/op
BenchmarkTryParseIntSlice 121.2 ns/op 0 B/op, 0 alloc/op
BenchmarkTryParseStringSlice 34.9 ns/op 0 B/op, 0 alloc/op

Notes:

  • Static JSON responses are down to a single allocation on the request path.
  • Param and catch-all routing become 0 alloc when params are pooled, which is already how Application runs.
  • Pre-encoded JSON (json.RawMessage) has a dedicated write fast path.
  • TryParseJSONBodyFast is the opt-in fast path for JSON request bodies when unknown-field rejection is not required.
  • Client response decoding has an explicit raw-body fast path via *web.RawBody.
  • Binary and avro responses have direct fast paths.
  • Slice parsing hot paths avoid strings.Split and now run with 0 alloc.
Benchmark Workflow

Run the current benchmark suite:

go test -run '^$' -bench 'Benchmark(ServeHTTP|TreeGetValue|TryParse|TryInt|TryUint|TryBool|Post(JSON|Bytes)|DoReqWithClient(Struct|RawBody)|CtxWriteBinaryReader)' -benchmem ./...

Compare current results against the committed baseline:

./bench/compare.sh

Refresh the committed baseline:

./bench/update_baseline.sh

Generate a Markdown benchmark snapshot ready to paste into the README:

./bench/snapshot.sh

Update the benchmark snapshot blocks in README.md and README_CN.md:

./bench/update_snapshot_readme.sh

Useful overrides:

COUNT=3 ./bench/compare.sh
BENCH_EXPR='BenchmarkServeHTTP(StaticJSON|PathParamJSON)$' ./bench/compare.sh
CURRENT_FILE=./bench/servehttp.txt COUNT=3 ./bench/compare.sh
SHOW_MISSING=1 ./bench/compare.sh
COUNT=3 ./bench/update_baseline.sh
COUNT=3 ./bench/snapshot.sh
COUNT=3 ./bench/update_snapshot_readme.sh

Files:

Performance Guidelines
  • Prefer []byte or web.AvroMarshaler for binary/avro responses.
  • Prefer PostBytes/PutBytes/PatchBytes/DoBytes when the request body is already encoded.
  • Prefer *WithClient helpers when you need tuned timeouts, connection pooling, or a custom transport.
  • Reuse destination slices when calling TryParse(..., &slice) in hot paths.
  • Prefer pooled param paths if you benchmark routing in isolation; the framework already does this in normal request handling.
  • Treat single benchmark runs as noisy. Use the baseline comparison script for direction, not intuition.
Quick Start
package main

import (
	"log"
	"net/http"

	"pkg.gostartkit.com/web"
)

func main() {
	app := web.New()

	app.Get("/health", func(c *web.Ctx) (any, error) {
		return map[string]string{"status": "ok"}, nil
	})

	log.Fatal(app.ListenAndServe("tcp", ":8080"))
}
API Index
  • web.New() *Application
  • route registration:
    • Get, Post, Put, Patch, Delete, Head, Options, Handle
  • framework composition:
    • Use, Group, SetErrorHandler, RegisterReader, RegisterWriter
  • server lifecycle:
    • ListenAndServe, ListenAndServeTLS, Shutdown
  • helpers:
    • ServeFiles, Redirect, TryParse(...), TryXxx(...), JSONErrorHandler
  • context (*Ctx) common methods:
    • request: Method, Path, Query, Param, Body, ContentType, BearerToken, RequestID
    • parse: TryParseBody, TryParseJSONBodyFast, TryParseParam, TryParseQuery, TryParseForm
    • response: SetHeader, SetCookie, AllowCredentials, content negotiation via Accept
API Quick Reference (EN)
Area API Description
Application New() Create app instance
Application Get/Post/Put/Patch/Delete/Head/Options(path, handler) Register route handler
Application Handle(method, path, handler) Register route handler for an arbitrary HTTP method
Application Use(middleware...) Apply app-level middleware to subsequently registered routes
Application Group(prefix, middleware...) Create route groups with shared prefix and middleware
Application SetErrorHandler(handler) Install a custom route error handler
Application RegisterReader(contentType, reader) Override request decoding for a media type
Application RegisterWriter(contentType, writer) Override response encoding for a media type
Application ServeFiles("/static/*filepath", fs) Serve static files with catch-all path
Application ListenAndServe(network, addr, ...opts) Start HTTP server
Application ListenAndServeTLS(network, addr, tlsConfig, ...opts) Start HTTPS server
Application Shutdown(ctx) Graceful shutdown
Context Param(name), Query(name), Form(name), RequestID() Read path/query/form values and middleware-provided request ID
Context TryParseBody(v) Parse request body by content type (JSON/GOB/XML)
Context TryParseJSONBodyFast(v) Fast JSON body parse using pooled buffer + json.Unmarshal
Context TryParseParam/Query/Form(name, &v) Parse string values into typed value
Context SetHeader, SetCookie, SetContentType, SetStatus Write response headers and override the default success status
Context Request(), ResponseWriter(), Context() Access raw HTTP objects
Middleware RequestID, Recover, RecoverWithOptions, Timeout, AccessLog, AccessLogWithOptions Built-in opt-in middleware helpers
Client Get/Post/Put/Patch/Delete/Do HTTP client helpers using http.DefaultClient
Client GetWithClient/PostWithClient/PutWithClient/PatchWithClient/DeleteWithClient/DoWithClient HTTP helpers with explicit *http.Client
Client DoReq/DoReqWithClient Execute prepared requests and decode JSON or RawBody responses
Client PostBytes/PutBytes/PatchBytes/DoBytes Send pre-encoded request bodies without JSON encoding
Client PostBytesWithClient/PutBytesWithClient/PatchBytesWithClient/DoBytesWithClient Pre-encoded body helpers with explicit *http.Client
Client TryGet/TryPost/TryPut/TryPatch/TryDelete/TryDo HTTP helpers with retry loop
Client TryGetWithClient/TryPostWithClient/TryPutWithClient/TryPatchWithClient/TryDeleteWithClient/TryDoWithClient Retry helpers with explicit *http.Client
Client TryPostBytes/TryPutBytes/TryPatchBytes/TryDoBytes Retry-capable helpers for pre-encoded request bodies
Client TryPostBytesWithClient/TryPutBytesWithClient/TryPatchBytesWithClient/TryDoBytesWithClient Retry-capable pre-encoded helpers with explicit *http.Client
Error NewErr(code, msg) Error with HTTP status code
Error Redirect(url, code) Return redirect response from handler
Error JSONErrorHandler(includeRequestID) Write structured JSON API errors
Response Behavior
  • Handler return value controls response:
    • (nil, nil) -> 204 No Content
    • (value, nil) -> 200 OK
    • call c.SetStatus(code) to explicitly override the default success status
    • (_, err) -> status code from framework error type, body contains err.Error()
  • Response format is selected by request Accept header:
    • application/json
    • application/x-gob
    • application/xml
    • application/octet-stream
    • application/x-avro
Routing Behavior
  • Static, param, and catch-all segments can coexist at the same tree level.
  • Match priority is fixed and does not depend on registration order:
    • static > param > catch-all
  • Catch-all routes are still only allowed at the end of the path.
  • Invalid wildcard combinations remain rejected at registration time.

This makes common REST route sets work without handler-level catch-all dispatch:

app.Get("/organizations/:id/devices/bulk/disable", bulkDisable)
app.Get("/organizations/:id/devices/provision", provision)
app.Get("/organizations/:id/devices/config/rollout", configRollout)
app.Get("/organizations/:id/devices/:device_id", showDevice)

With the routes above:

  • GET /organizations/1/devices/provision matches the static route.
  • GET /organizations/1/devices/42 matches the param route.
  • Registering :device_id before or after provision produces the same result.
Modern Framework Features
  • Middleware and route groups are registration-time features:
    • app.Use(...)
    • app.Group("/api", ...)
    • group-local Use(...)
  • Built-in middleware is explicit opt-in:
    • RequestID
    • Recover
    • RecoverWithOptions
    • Timeout
    • AccessLog
    • AccessLogWithOptions
  • Structured API errors are opt-in via SetErrorHandler(JSONErrorHandler(...))
  • Reader/writer overrides are media-type specific and do not affect the default hot path unless registered
app := web.New()
app.Use(web.RequestID("", nil), web.Recover(nil))
app.SetErrorHandler(web.JSONErrorHandler(true))

api := app.Group("/api", web.Timeout(2*time.Second))
api.Get("/users/:id", func(c *web.Ctx) (any, error) {
	return map[string]string{
		"id":         c.Param("id"),
		"request_id": c.RequestID(),
	}, nil
})

For finer control, use the options-based middleware variants:

app.Use(
	web.RecoverWithOptions(web.RecoverOptions{
		DefaultStatus: http.StatusServiceUnavailable,
		DefaultBody:   "UNAVAILABLE",
	}),
	web.AccessLogWithOptions(web.AccessLogOptions{
		Log: func(c *web.Ctx, entry web.AccessLogEntry) {
			// route-aware access logging hook
		},
	}),
)
Compatibility / Breaking Changes
  • Try* retry semantics updated:
    • retry <= 0 now still performs one request attempt.
    • retry loop stops early for ErrUnauthorized, ErrForbidden, and ErrBadRequest (including wrapped).
  • TryDo now supports safe body replay across retries (request body is buffered once and recreated per attempt).
  • Raw body helpers added:
    • PostBytes, PutBytes, PatchBytes, DoBytes
    • TryPostBytes, TryPutBytes, TryPatchBytes, TryDoBytes
    • default request headers are Content-Type: application/octet-stream and Accept: application/json
  • Explicit client helpers added:
    • DoReqWithClient, DoWithClient, DoBytesWithClient
    • wrapper and retry variants for Get/Post/Put/Patch/Delete
    • use these when transport-level performance tuning matters
  • Raw response fast path added:
    • DoReq / DoReqWithClient now recognize *web.RawBody
    • existing JSON destinations like []byte and json.RawMessage keep their original JSON semantics
  • Ctx.writeBinary and Ctx.writeAvro are implemented:
    • previous behavior for these media types was ErrNotImplemented.
    • now they support fast-path direct writing (see Binary / Avro response section).
  • Redirect usage:
    • returning only ErrMovedPermanently does not set Location.
    • use web.Redirect(url, code) to generate proper redirect response headers.
  • Header negotiation improvement:
    • Accept/Content-Type values with parameters (e.g. application/json; charset=utf-8) are now parsed correctly.

Migration tips:

  • If you relied on retry=0 to skip outbound call, replace with explicit conditional in caller.
  • If your handlers used application/octet-stream or application/x-avro, you can now return []byte, io.Reader, or custom marshaler types directly.
  • For redirects, migrate to web.Redirect(...) for predictable behavior.
Binary / Avro response

Ctx.writeBinary and Ctx.writeAvro are optimized for fast paths.

  • Binary fast-path input types:
    • []byte
    • string
    • *bytes.Buffer
    • io.Reader
    • encoding.BinaryMarshaler
  • Avro fast-path input types:
    • web.AvroMarshaler
    • falls back to binary writer for the same input types above
type Event struct {
	Raw []byte
}

func (e Event) MarshalAvro() ([]byte, error) {
	return e.Raw, nil
}

app.Get("/payload", func(c *web.Ctx) (any, error) {
	// Client sends: Accept: application/x-avro
	return Event{Raw: []byte{0xAA, 0xBB}}, nil
})
Redirect helper

Use web.Redirect(url, code) to return redirect responses.

app.Get("/old", func(c *web.Ctx) (any, error) {
	return web.Redirect("/new", http.StatusMovedPermanently)
})
HTTP client retry behavior

TryGet, TryPost, TryPut, TryPatch, TryDelete, TryDo:

  • retry <= 0 still performs at least one request.
  • retries stop early for non-retriable errors:
    • ErrUnauthorized
    • ErrForbidden
    • ErrBadRequest (including wrapped)
  • TryDo safely retries with request body replay (body is cached once and recreated per attempt).
Fast JSON Body Parse

Use TryParseJSONBodyFast when the request body is JSON and unknown-field rejection is not required.

app.Post("/ingest", func(c *web.Ctx) (any, error) {
	var req struct {
		ID int `json:"id"`
	}

	if err := c.TryParseJSONBodyFast(&req); err != nil {
		return nil, err
	}

	return struct {
		Ok bool `json:"ok"`
	}{Ok: true}, nil
})
Client Raw Response

Use DoReqWithClient with *web.RawBody when you want the response payload without JSON decoding cost.

req, _ := http.NewRequest(http.MethodGet, "https://example.com/data", nil)

var raw web.RawBody
if err := web.DoReqWithClient(client, req, &raw, nil); err != nil {
	panic(err)
}
Notes
  • Best performance for param/catch-all routing is achieved when params are pooled (already used in Application).
  • For binary/avro responses, prefer returning []byte or implementing web.AvroMarshaler to avoid extra encoding overhead.
  • TryParseBody currently supports JSON/GOB/XML only.
Acknowledgments

Thanks to all open-source projects, I’ve learned a lot from them.

Special thanks to:

  • httprouter: A high-performance HTTP router that inspired the routing logic in this project.
  • web: A lightweight web framework that provided insights into efficient server design.

Documentation

Overview

Package web implements a performance-oriented HTTP framework for Go.

The package is designed around a small, explicit core:

  • tree-based routing for static, parameter, and catch-all paths
  • pooled request context and pooled route params
  • explicit request parsing and response writing
  • opt-in middleware, route groups, and structured error handling
  • integrated HTTP client helpers with retry and raw-body fast paths

The default request path is intentionally tight. Additional framework features such as middleware, custom readers/writers, structured JSON error output, and client transport tuning are all opt-in so that unused capabilities do not add work to the hot path.

Quick start:

package main

import (
	"log"

	"pkg.gostartkit.com/web"
)

func main() {
	app := web.New()

	app.Get("/health", func(c *web.Ctx) (any, error) {
		return map[string]string{"status": "ok"}, nil
	})

	log.Fatal(app.ListenAndServe("tcp", ":8080"))
}

Modern framework composition:

app := web.New()
app.Use(web.RequestID("", nil), web.Recover(nil))
app.SetErrorHandler(web.JSONErrorHandler(true))

api := app.Group("/api", web.Timeout(2*time.Second))
api.Get("/users/:id", func(c *web.Ctx) (any, error) {
	return map[string]string{
		"id":         c.Param("id"),
		"request_id": c.RequestID(),
	}, nil
})

Request and response model:

Handlers use the form:

func(c *web.Ctx) (any, error)

The returned value controls the default response semantics:

  • (nil, nil) -> 204 No Content
  • (value, nil) -> 200 OK
  • call c.SetStatus(code) to explicitly override the default success status
  • (_, err) -> status inferred from framework error type

Request bodies are parsed from Content-Type using Ctx.TryParseBody, or Ctx.TryParseJSONBodyFast when unknown-field rejection is not required.

Responses are negotiated from Accept and support JSON, GOB, XML, binary, and Avro. Pre-encoded JSON can be returned as json.RawMessage. Raw client response bytes use the explicit RawBody type.

Performance guidance:

  • Prefer []byte or AvroMarshaler for binary and Avro output
  • Prefer PostBytes/PutBytes/PatchBytes/DoBytes when request payloads are already encoded
  • Reuse destination slices in TryParse hot paths
  • Use explicit *WithClient helpers when transport-level tuning matters

See README.md and README_CN.md for benchmark snapshots, compatibility notes, and the full API surface.

Index

Constants

View Source
const (
	QueryType    = "type"
	QueryFilter  = "filter"
	QueryOrderBy = "orderBy"
	QueryPage    = "page"
	QueryId      = "id"
	QueryLimit   = "limit"
	HeaderAttrs  = "attrs"
	TokenKey     = "tk"
)
View Source
const DefaultRequestIDHeader = "X-Request-Id"

DefaultRequestIDHeader is the default request/response header used by RequestID middleware.

Variables

View Source
var (
	// ErrMovedPermanently represents an HTTP 301 Moved Permanently error.
	// This error indicates that the requested resource has been permanently moved to a new URL.
	// Typically used in web applications when a redirect to a new permanent location is required.
	// Example usage: return this error when a webpage or API endpoint has been relocated permanently,
	// and the client should update its bookmarks or references accordingly.
	ErrMovedPermanently = NewErr(http.StatusMovedPermanently, "MOVEDPERMANENTLY")

	// ErrFound represents an HTTP 302 Found error.
	// This error signifies that the requested resource has been temporarily moved to a different URL.
	// Commonly used in web redirection scenarios where the resource is available at a different location
	// for the time being, but the original URL might still be valid in the future.
	// Example: a temporary redirect during site maintenance.
	ErrFound = NewErr(http.StatusFound, "FOUND")

	// ErrTemporaryRedirect represents an HTTP 307 Temporary Redirect error.
	// This error indicates a temporary redirection where the client should retry the request
	// at a different URL while preserving the original request method (e.g., POST remains POST).
	// Useful in scenarios like load balancing or temporary resource unavailability.
	// Note: Unlike 302, 307 explicitly requires maintaining the HTTP method.
	ErrTemporaryRedirect = NewErr(http.StatusTemporaryRedirect, "TEMPORARYREDIRECT")

	// ErrPermanentRedirect represents an HTTP 308 Permanent Redirect error.
	// This error denotes a permanent redirection to a new URL, requiring the client to update its
	// references while preserving the original request method.
	// Suitable for permanent resource relocation where the method (e.g., POST, GET) must remain unchanged.
	// Example: API endpoint migrations with strict method requirements.
	ErrPermanentRedirect = NewErr(http.StatusPermanentRedirect, "PERMANENTREDIRECT")

	// ErrBadRequest represents an HTTP 400 Bad Request error.
	// This error is returned when the server cannot process the request due to malformed syntax,
	// invalid parameters, or client-side errors in the request payload.
	// Use this when validating input fails or the request format is incorrect.
	// Example: malformed JSON in an API request.
	ErrBadRequest = NewErr(http.StatusBadRequest, "BADREQUEST")

	// ErrRequestTimeout represents an HTTP 408 Request Timeout error.
	// This error is returned when request processing exceeds a configured deadline.
	ErrRequestTimeout = NewErr(http.StatusRequestTimeout, "REQUESTTIMEOUT")

	// ErrUnauthorized represents an HTTP 401 Unauthorized error.
	// This error indicates that the request lacks valid authentication credentials (e.g., token, username/password).
	// Return this when a user attempts to access a protected resource without proper authorization.
	// Note: Often paired with a WWW-Authenticate header in HTTP responses.
	// Example: missing or invalid API key.
	ErrUnauthorized = NewErr(http.StatusUnauthorized, "UNAUTHORIZED")

	// ErrForbidden represents an HTTP 403 Forbidden error.
	// This error signifies that the server understood the request, but the client is not allowed to access
	// the resource, even with valid credentials (e.g., insufficient permissions).
	// Use this for access control violations.
	// Example: a user trying to access an admin-only endpoint.
	ErrForbidden = NewErr(http.StatusForbidden, "FORBIDDEN")

	// ErrNotFound represents an HTTP 404 Not Found error.
	// This error indicates that the requested resource could not be found on the server.
	// Commonly used when a webpage, file, or API endpoint does not exist or has been removed.
	// Example: requesting a non-existent user profile by ID.
	ErrNotFound = NewErr(http.StatusNotFound, "NOTFOUND")

	// ErrMethodNotAllowed represents an HTTP 405 Method Not Allowed error.
	// This error is returned when the HTTP method used (e.g., POST, GET) is not supported for the requested resource.
	// Useful in APIs to enforce allowed methods on endpoints.
	// Example: sending a POST request to a GET-only resource.
	// Tip: Responses typically include an Allow header listing permitted methods.
	ErrMethodNotAllowed = NewErr(http.StatusMethodNotAllowed, "METHODNOTALLOWED")

	// ErrNotImplemented represents an HTTP 501 Not Implemented error.
	// This error indicates that the server does not support the functionality required to fulfill the request.
	// Often used for unimplemented features or unsupported HTTP methods in development.
	// Example: an API endpoint planned but not yet coded.
	ErrNotImplemented = NewErr(http.StatusNotImplemented, "NOTIMPLEMENTED")

	// ErrContentType indicates that the content-type of the request is not supported.
	// This error is returned when the server cannot process the request due to an unsupported media type
	// in the Content-Type header (e.g., expecting JSON but receiving XML).
	// Use this in APIs or handlers requiring specific content types.
	// Example: rejecting a request with "text/plain" when "application/json" is required.
	ErrContentType = NewErr(http.StatusBadRequest, "CONTENTTYPENOTSUPPORTED")

	// ErrCors indicates that a cross-origin request was blocked.
	// This error is triggered when a request violates Cross-Origin Resource Sharing (CORS) policies,
	// such as mismatched origins or missing CORS headers.
	// Common in web applications interacting with APIs from different domains.
	// Example: a frontend app on localhost trying to access a restricted API.
	ErrCors = NewErr(http.StatusBadRequest, "CROSSORIGINREQUESTBLOCKED")

	// ErrUnexpected indicates an unexpected error occurred.
	// This is a catch-all error for unanticipated issues that don’t fit specific categories,
	// such as internal server errors or unhandled edge cases.
	// Use sparingly; prefer specific errors when possible.
	// Example: a third-party service unexpectedly fails.
	ErrUnexpected = NewErr(http.StatusBadRequest, "UNEXPECTED")

	// ErrNotVerified indicates that an object or entity has not been verified.
	// This error is returned when a required verification step (e.g., email, identity) has not been completed.
	// Useful in workflows requiring validation or authentication checks.
	// Example: attempting to use an unverified user account.
	ErrNotVerified = NewErr(http.StatusBadRequest, "NOTVERIFIED")

	// ErrInvalid indicates that an object or input is invalid.
	// This error signifies that the provided data or resource does not meet expected criteria,
	// such as format, range, or logical constraints.
	// Use this for general validation failures not covered by specific errors like ErrBadRequest.
	// Example: an invalid date string in a form submission.
	ErrInvalid = NewErr(http.StatusBadRequest, "INVALID")

	// ErrServerNotInitialized is returned when attempting to perform operations (e.g., Shutdown)
	// on an Application instance whose HTTP server (app.srv) has not been initialized.
	// This typically occurs if the serve method has not been called or if the server was explicitly reset.
	ErrServerNotInitialized = NewErr(http.StatusServiceUnavailable, "SERVERNOTINITIALIZED")
)

Functions

func Delete

func Delete(ctx context.Context, url string, accessToken string, v any, before ...func(r *http.Request)) error

Delete http delete

func DeleteWithClient added in v0.1.35

func DeleteWithClient(client *http.Client, ctx context.Context, url string, accessToken string, v any, before ...func(r *http.Request)) error

DeleteWithClient http delete with explicit client

func Do added in v0.1.17

func Do(ctx context.Context, method string, url string, accessToken string, body io.Reader, v any, before ...func(r *http.Request)) error

Do do http request

func DoBytes added in v0.1.35

func DoBytes(ctx context.Context, method string, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

DoBytes sends a request with a pre-encoded body.

func DoBytesWithClient added in v0.1.35

func DoBytesWithClient(client *http.Client, ctx context.Context, method string, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

DoBytesWithClient sends a request with a pre-encoded body and explicit client.

func DoReq added in v0.1.29

func DoReq(req *http.Request, v any, failure func(statusCode int, body io.ReadCloser) error) error

DoReq do http request

func DoReqWithClient added in v0.1.35

func DoReqWithClient(client *http.Client, req *http.Request, v any, failure func(statusCode int, body io.ReadCloser) error) error

DoReqWithClient do http request with explicit client

func DoWithClient added in v0.1.35

func DoWithClient(client *http.Client, ctx context.Context, method string, url string, accessToken string, body io.Reader, v any, before ...func(r *http.Request)) error

DoWithClient do http request with explicit client

func Get

func Get(ctx context.Context, url string, accessToken string, v any, before ...func(r *http.Request)) error

Get http get

func GetWithClient added in v0.1.35

func GetWithClient(client *http.Client, ctx context.Context, url string, accessToken string, v any, before ...func(r *http.Request)) error

GetWithClient http get with explicit client

func IsErrFn added in v0.1.34

func IsErrFn(err error) bool

func NewErr added in v0.1.33

func NewErr(code int, msg string) error

func NewErrFn added in v0.1.33

func NewErrFn(code int, msg string, cb Fn) error

func Patch

func Patch(ctx context.Context, url string, accessToken string, data any, v any, before ...func(r *http.Request)) error

Patch http patch

func PatchBytes added in v0.1.35

func PatchBytes(ctx context.Context, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

PatchBytes http patch with raw bytes body

func PatchBytesWithClient added in v0.1.35

func PatchBytesWithClient(client *http.Client, ctx context.Context, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

PatchBytesWithClient http patch with raw bytes body and explicit client

func PatchWithClient added in v0.1.35

func PatchWithClient(client *http.Client, ctx context.Context, url string, accessToken string, data any, v any, before ...func(r *http.Request)) error

PatchWithClient http patch with explicit client

func Post

func Post(ctx context.Context, url string, accessToken string, data any, v any, before ...func(r *http.Request)) error

Post http post

func PostBytes added in v0.1.35

func PostBytes(ctx context.Context, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

PostBytes http post with raw bytes body

func PostBytesWithClient added in v0.1.35

func PostBytesWithClient(client *http.Client, ctx context.Context, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

PostBytesWithClient http post with raw bytes body and explicit client

func PostWithClient added in v0.1.35

func PostWithClient(client *http.Client, ctx context.Context, url string, accessToken string, data any, v any, before ...func(r *http.Request)) error

PostWithClient http post with explicit client

func Put

func Put(ctx context.Context, url string, accessToken string, data any, v any, before ...func(r *http.Request)) error

Put http put

func PutBytes added in v0.1.35

func PutBytes(ctx context.Context, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

PutBytes http put with raw bytes body

func PutBytesWithClient added in v0.1.35

func PutBytesWithClient(client *http.Client, ctx context.Context, url string, accessToken string, body []byte, v any, before ...func(r *http.Request)) error

PutBytesWithClient http put with raw bytes body and explicit client

func PutWithClient added in v0.1.35

func PutWithClient(client *http.Client, ctx context.Context, url string, accessToken string, data any, v any, before ...func(r *http.Request)) error

PutWithClient http put with explicit client

func Redirect added in v0.1.23

func Redirect(url string, code int) (any, error)

Redirect helper function for return url and redirect error

func RequestIDFromContext added in v0.1.35

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID stored by RequestID middleware.

func TryBool added in v0.1.33

func TryBool(val string) (bool, error)

func TryDelete added in v0.1.28

func TryDelete(ctx context.Context, url string, accessToken string, v any, retry int, before ...func(r *http.Request)) error

TryDelete

func TryDeleteWithClient added in v0.1.35

func TryDeleteWithClient(client *http.Client, ctx context.Context, url string, accessToken string, v any, retry int, before ...func(r *http.Request)) error

TryDeleteWithClient

func TryDo added in v0.1.28

func TryDo(ctx context.Context, method string, url string, accessToken string, body io.Reader, v any, retry int, before ...func(r *http.Request)) error

TryDo

func TryDoBytes added in v0.1.35

func TryDoBytes(ctx context.Context, method string, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryDoBytes

func TryDoBytesWithClient added in v0.1.35

func TryDoBytesWithClient(client *http.Client, ctx context.Context, method string, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryDoBytesWithClient

func TryDoWithClient added in v0.1.35

func TryDoWithClient(client *http.Client, ctx context.Context, method string, url string, accessToken string, body io.Reader, v any, retry int, before ...func(r *http.Request)) error

TryDoWithClient

func TryFloat32 added in v0.1.33

func TryFloat32(val string) (float32, error)

func TryFloat64 added in v0.1.33

func TryFloat64(val string) (float64, error)

func TryGet added in v0.1.28

func TryGet(ctx context.Context, url string, accessToken string, v any, retry int, before ...func(r *http.Request)) error

TryGet

func TryGetWithClient added in v0.1.35

func TryGetWithClient(client *http.Client, ctx context.Context, url string, accessToken string, v any, retry int, before ...func(r *http.Request)) error

TryGetWithClient

func TryInt added in v0.1.33

func TryInt(val string) (int, error)

func TryInt8 added in v0.1.33

func TryInt8(val string) (int8, error)

func TryInt16 added in v0.1.33

func TryInt16(val string) (int16, error)

func TryInt32 added in v0.1.33

func TryInt32(val string) (int32, error)

func TryInt64 added in v0.1.33

func TryInt64(val string) (int64, error)

func TryParse

func TryParse(val string, v any) error

TryParse try parse val to v

func TryPatch added in v0.1.28

func TryPatch(ctx context.Context, url string, accessToken string, data any, v any, retry int, before ...func(r *http.Request)) error

TryPatch

func TryPatchBytes added in v0.1.35

func TryPatchBytes(ctx context.Context, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryPatchBytes

func TryPatchBytesWithClient added in v0.1.35

func TryPatchBytesWithClient(client *http.Client, ctx context.Context, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryPatchBytesWithClient

func TryPatchWithClient added in v0.1.35

func TryPatchWithClient(client *http.Client, ctx context.Context, url string, accessToken string, data any, v any, retry int, before ...func(r *http.Request)) error

TryPatchWithClient

func TryPost added in v0.1.28

func TryPost(ctx context.Context, url string, accessToken string, data any, v any, retry int, before ...func(r *http.Request)) error

TryPost

func TryPostBytes added in v0.1.35

func TryPostBytes(ctx context.Context, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryPostBytes

func TryPostBytesWithClient added in v0.1.35

func TryPostBytesWithClient(client *http.Client, ctx context.Context, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryPostBytesWithClient

func TryPostWithClient added in v0.1.35

func TryPostWithClient(client *http.Client, ctx context.Context, url string, accessToken string, data any, v any, retry int, before ...func(r *http.Request)) error

TryPostWithClient

func TryPut added in v0.1.28

func TryPut(ctx context.Context, url string, accessToken string, data any, v any, retry int, before ...func(r *http.Request)) error

TryPut

func TryPutBytes added in v0.1.35

func TryPutBytes(ctx context.Context, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryPutBytes

func TryPutBytesWithClient added in v0.1.35

func TryPutBytesWithClient(client *http.Client, ctx context.Context, url string, accessToken string, body []byte, v any, retry int, before ...func(r *http.Request)) error

TryPutBytesWithClient

func TryPutWithClient added in v0.1.35

func TryPutWithClient(client *http.Client, ctx context.Context, url string, accessToken string, data any, v any, retry int, before ...func(r *http.Request)) error

TryPutWithClient

func TryUint added in v0.1.33

func TryUint(val string) (uint, error)

func TryUint8 added in v0.1.33

func TryUint8(val string) (uint8, error)

func TryUint16 added in v0.1.33

func TryUint16(val string) (uint16, error)

func TryUint32 added in v0.1.33

func TryUint32(val string) (uint32, error)

func TryUint64 added in v0.1.33

func TryUint64(val string) (uint64, error)

Types

type AccessLogEntry added in v0.1.35

type AccessLogEntry struct {
	Status   int
	Duration time.Duration
	Error    error
}

AccessLogEntry is the payload emitted by AccessLogWithOptions.

type AccessLogOptions added in v0.1.35

type AccessLogOptions struct {
	Log          func(c *Ctx, entry AccessLogEntry)
	Now          func() time.Time
	StatusMapper func(c *Ctx, val any, err error) int
}

AccessLogOptions configures access logging middleware behavior.

type Application

type Application struct {
	NotFound         http.Handler
	MethodNotAllowed http.Handler
	// contains filtered or unexported fields
}

Application is type of a web.Application

func New added in v0.1.33

func New() *Application

New return *web.Application

func (*Application) Delete

func (app *Application) Delete(path string, next Next)

Delete method

func (*Application) Errf added in v0.1.33

func (app *Application) Errf(format string, v ...any)

Errf write err log

func (*Application) Get

func (app *Application) Get(path string, next Next)

Get method

func (*Application) Group added in v0.1.35

func (app *Application) Group(prefix string, middleware ...Middleware) *RouteGroup

Group creates a route group with a shared prefix and middleware chain.

func (*Application) Handle added in v0.1.35

func (app *Application) Handle(method string, path string, next Next, middleware ...Middleware)

Handle registers a route for an arbitrary HTTP method.

func (*Application) Head

func (app *Application) Head(path string, cb Next)

Head method

func (*Application) Inspect

func (app *Application) Inspect() string

Inspect method

func (*Application) ListenAndServe

func (app *Application) ListenAndServe(network string, addr string, fns ...func(*http.Server)) error

ListenAndServe Serve with options on addr

func (*Application) ListenAndServeTLS

func (app *Application) ListenAndServeTLS(network string, addr string, tlsConfig *tls.Config, fns ...func(*http.Server)) error

ListenAndServeTLS Serve with tls and options on addr

func (*Application) Logf added in v0.1.33

func (app *Application) Logf(format string, v ...any)

Logf write info log

func (*Application) Options

func (app *Application) Options(path string, next Next)

Options method

func (*Application) Patch

func (app *Application) Patch(path string, next Next)

Patch method

func (*Application) Post

func (app *Application) Post(path string, next Next)

Post method

func (*Application) Put

func (app *Application) Put(path string, next Next)

Put method

func (*Application) RegisterReader added in v0.1.35

func (app *Application) RegisterReader(contentType string, reader Reader) error

RegisterReader registers a request body reader for a supported content type.

func (*Application) RegisterWriter added in v0.1.35

func (app *Application) RegisterWriter(contentType string, writer Writer) error

RegisterWriter registers a response writer for a supported accept/content type.

func (*Application) ServeFiles

func (app *Application) ServeFiles(path string, root http.FileSystem)

ServeFiles registers a route to serve static files from the specified file system under the given path pattern. The path must end with "/*filepath" to capture file paths dynamically. It panics if the path pattern is invalid, ensuring correct configuration during initialization.

Parameters:

  • path: The URL path pattern (e.g., "/static/*filepath") to match file requests. Must end with "/*filepath" to extract the file path as a parameter.
  • root: The http.FileSystem to serve files from (e.g., http.Dir("./static")).

Panics:

  • If the path is shorter than 10 characters or does not end with "/*filepath".

func (*Application) ServeHTTP

func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP w, r

func (*Application) SetCORS added in v0.1.13

func (app *Application) SetCORS(cors Cors)

SetCORS set CORS

func (*Application) SetErrLogger added in v0.1.33

func (app *Application) SetErrLogger(logger *log.Logger)

SetErrLogger set err logger

func (*Application) SetErrorHandler added in v0.1.35

func (app *Application) SetErrorHandler(handler ErrorHandler)

SetErrorHandler sets a custom route error handler.

func (*Application) SetInfoLogger added in v0.1.33

func (app *Application) SetInfoLogger(logger *log.Logger)

SetInfoLogger set info logger

func (*Application) SetPanic

func (app *Application) SetPanic(panic Panic)

SetPanic set Panic

func (*Application) Shutdown added in v0.1.33

func (app *Application) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the HTTP server, allowing active connections to complete. It returns an error if the server is not initialized, ensuring callers can detect invalid states.

Parameters:

  • ctx: Context controlling the shutdown timeout. If the context expires before shutdown completes, remaining connections may be forcibly closed.

Returns:

  • error: Returns ErrServerNotInitialized if the server is not initialized, or any error from http.Server.Shutdown (e.g., context timeout). Returns nil if shutdown completes successfully.

func (*Application) Use

func (app *Application) Use(middleware ...Middleware)

Use appends application middleware for subsequently registered routes.

type AvroMarshaler added in v0.1.34

type AvroMarshaler interface {
	MarshalAvro() ([]byte, error)
}

AvroMarshaler allows custom zero-reflection avro serialization in hot paths.

type Chain added in v0.1.12

type Chain []Middleware

Chain middleware chain

type Cors added in v0.1.22

type Cors func(set func(key string, value string), origin string, allow []string)

Cors

type Ctx added in v0.1.12

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

Ctx represents the context for a web request, holding relevant request data and response methods.

func (*Ctx) Accept added in v0.1.12

func (c *Ctx) Accept() string

Accept get Accept from header

func (*Ctx) AllowCredentials added in v0.1.31

func (c *Ctx) AllowCredentials()

AllowCredentials sets the "Access-Control-Allow-Credentials" header to true in the response.

func (*Ctx) BearerToken added in v0.1.15

func (c *Ctx) BearerToken() string

BearerToken retrieves the Bearer token from the Authorization header.

func (*Ctx) Body added in v0.1.12

func (c *Ctx) Body() io.ReadCloser

Body returns the request body.

func (*Ctx) ContentType added in v0.1.12

func (c *Ctx) ContentType() string

ContentType get Content-Type from header

func (*Ctx) Context added in v0.1.32

func (c *Ctx) Context() context.Context

Context returns the context of the request.

func (*Ctx) Flush added in v0.1.34

func (c *Ctx) Flush()

Flush implements http.Flusher when supported by the underlying writer.

func (*Ctx) Flusher added in v0.1.32

func (c *Ctx) Flusher() http.Flusher

Flusher returns the http.Flusher interface if the response writer supports it. This is useful for enabling HTTP/1.1 chunked transfer encoding. It allows the server to send data to the client in chunks, rather than waiting for the entire response to be ready. This is particularly useful for streaming data or for long-lived connections. If the response writer does not support chunked transfer encoding, it returns nil.

func (*Ctx) Form added in v0.1.12

func (c *Ctx) Form(name string) string

Form retrieves a form value by name from the request.

func (*Ctx) FormBool added in v0.1.13

func (c *Ctx) FormBool(name string) (bool, error)

FormBool attempts to parse a bool from form value by name.

func (*Ctx) FormFile added in v0.1.18

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

FormFile retrieves the first file uploaded for the specified form key. It calls Request.ParseMultipartForm and Request.ParseForm if needed.

func (*Ctx) FormFloat32 added in v0.1.13

func (c *Ctx) FormFloat32(name string) (float32, error)

FormFloat32 attempts to parse a float32 from form value by name.

func (*Ctx) FormFloat64 added in v0.1.13

func (c *Ctx) FormFloat64(name string) (float64, error)

FormFloat64 attempts to parse a float64 from form value by name.

func (*Ctx) FormInt added in v0.1.13

func (c *Ctx) FormInt(name string) (int, error)

FormIn attempts to parse a int from form value by name.

func (*Ctx) FormInt8 added in v0.1.13

func (c *Ctx) FormInt8(name string) (int8, error)

FormInt8 attempts to parse a int8 from form value by name.

func (*Ctx) FormInt16 added in v0.1.13

func (c *Ctx) FormInt16(name string) (int16, error)

FormInt16 attempts to parse a int16 from form value by name.

func (*Ctx) FormInt32 added in v0.1.13

func (c *Ctx) FormInt32(name string) (int32, error)

FormInt32 attempts to parse a int32 from form value by name.

func (*Ctx) FormInt64 added in v0.1.13

func (c *Ctx) FormInt64(name string) (int64, error)

FormInt64 attempts to parse a int64 from form value by name.

func (*Ctx) FormUint added in v0.1.13

func (c *Ctx) FormUint(name string) (uint, error)

FormUint attempts to parse a uint from form value by name.

func (*Ctx) FormUint8 added in v0.1.13

func (c *Ctx) FormUint8(name string) (uint8, error)

FormUint8 attempts to parse a uint8 from form value by name.

func (*Ctx) FormUint16 added in v0.1.13

func (c *Ctx) FormUint16(name string) (uint16, error)

FormUint16 attempts to parse a uint16 from form value by name.

func (*Ctx) FormUint32 added in v0.1.13

func (c *Ctx) FormUint32(name string) (uint32, error)

FormUint32 attempts to parse a uint32 from form value by name.

func (*Ctx) FormUint64 added in v0.1.13

func (c *Ctx) FormUint64(name string) (uint64, error)

FormUint64 attempts to parse a uint64 from form value by name.

func (*Ctx) GetCookie added in v0.1.33

func (c *Ctx) GetCookie(name string) (*http.Cookie, error)

GetCookie returns the named cookie provided in the request or [ErrNoCookie] if not found. If multiple cookies match the given name, only one cookie will be returned.

func (*Ctx) GetHeader added in v0.1.33

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

GetHeader GetHeader header, short hand of r.Header.Get

func (*Ctx) Header added in v0.1.34

func (c *Ctx) Header() http.Header

Header implements http.ResponseWriter and proxies to the underlying writer.

func (*Ctx) Hijack added in v0.1.34

func (c *Ctx) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements http.Hijacker when supported by the underlying writer.

func (*Ctx) Hijacker added in v0.1.32

func (c *Ctx) Hijacker() http.Hijacker

Hijacker returns the http.Hijacker interface if the response writer supports it. This is useful for upgrading the connection to a different protocol, such as WebSocket. If the response writer does not support hijacking, it returns nil.

func (*Ctx) Host added in v0.1.12

func (c *Ctx) Host() string

Host returns the host from the request header.

func (*Ctx) Init added in v0.1.12

func (c *Ctx) Init(userId uint64)

Init initializes the context with user ID and user rights.

func (*Ctx) IsAjax added in v0.1.12

func (c *Ctx) IsAjax() bool

IsAjax checks if the request is an AJAX request based on the "X-Requested-With" header.

func (*Ctx) IsForm added in v0.1.34

func (c *Ctx) IsForm() bool

func (*Ctx) IsFormData deprecated added in v0.1.33

func (c *Ctx) IsFormData() bool

Deprecated: use IsForm() instead

func (*Ctx) Method added in v0.1.12

func (c *Ctx) Method() string

Method returns the HTTP method (GET, POST, etc.) used for the request.

func (*Ctx) Origin added in v0.1.15

func (c *Ctx) Origin() string

Origin returns the Origin header from the request.

func (*Ctx) Param added in v0.1.12

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

Param retrieves a parameter value by name from the Params.

func (*Ctx) ParamBool added in v0.1.13

func (c *Ctx) ParamBool(name string) (bool, error)

ParamBool attempts to parse a bool from the URL parameter by name.

func (*Ctx) ParamFloat32 added in v0.1.13

func (c *Ctx) ParamFloat32(name string) (float32, error)

ParamFloat32 attempts to parse a float32 from the URL parameter by name.

func (*Ctx) ParamFloat64 added in v0.1.13

func (c *Ctx) ParamFloat64(name string) (float64, error)

ParamFloat64 attempts to parse a float64 from the URL parameter by name.

func (*Ctx) ParamInt added in v0.1.13

func (c *Ctx) ParamInt(name string) (int, error)

ParamInt attempts to parse an integer from the URL parameter by name.

func (*Ctx) ParamInt8 added in v0.1.13

func (c *Ctx) ParamInt8(name string) (int8, error)

ParamInt8 attempts to parse an int8 from the URL parameter by name.

func (*Ctx) ParamInt16 added in v0.1.13

func (c *Ctx) ParamInt16(name string) (int16, error)

ParamInt16 attempts to parse an int16 from the URL parameter by name.

func (*Ctx) ParamInt32 added in v0.1.13

func (c *Ctx) ParamInt32(name string) (int32, error)

ParamInt32 attempts to parse an int32 from the URL parameter by name.

func (*Ctx) ParamInt64 added in v0.1.13

func (c *Ctx) ParamInt64(name string) (int64, error)

ParamInt64 attempts to parse an int64 from the URL parameter by name.

func (*Ctx) ParamUint added in v0.1.13

func (c *Ctx) ParamUint(name string) (uint, error)

ParamUint attempts to parse an unsigned integer from the URL parameter by name.

func (*Ctx) ParamUint8 added in v0.1.13

func (c *Ctx) ParamUint8(name string) (uint8, error)

ParamUint8 attempts to parse a uint8 from the URL parameter by name.

func (*Ctx) ParamUint16 added in v0.1.13

func (c *Ctx) ParamUint16(name string) (uint16, error)

ParamUint16 attempts to parse a uint16 from the URL parameter by name.

func (*Ctx) ParamUint32 added in v0.1.13

func (c *Ctx) ParamUint32(name string) (uint32, error)

ParamUint32 attempts to parse a uint32 from the URL parameter by name.

func (*Ctx) ParamUint64 added in v0.1.13

func (c *Ctx) ParamUint64(name string) (uint64, error)

ParamUint64 attempts to parse a uint64 from the URL parameter by name.

func (*Ctx) Path added in v0.1.12

func (c *Ctx) Path() string

Path returns the path from the request URL.

func (*Ctx) PostForm added in v0.1.33

func (c *Ctx) PostForm(name string) string

PostForm retrieves a form value by name from the request.

func (*Ctx) PostFormBool added in v0.1.33

func (c *Ctx) PostFormBool(name string) (bool, error)

PostFormBool attempts to parse a bool from PostForm value by name.

func (*Ctx) PostFormFloat32 added in v0.1.33

func (c *Ctx) PostFormFloat32(name string) (float32, error)

PostFormFloat32 attempts to parse a float32 from PostForm value by name.

func (*Ctx) PostFormFloat64 added in v0.1.33

func (c *Ctx) PostFormFloat64(name string) (float64, error)

PostFormFloat64 attempts to parse a float64 from PostForm value by name.

func (*Ctx) PostFormInt added in v0.1.33

func (c *Ctx) PostFormInt(name string) (int, error)

PostFormIn attempts to parse a int from PostForm value by name.

func (*Ctx) PostFormInt8 added in v0.1.33

func (c *Ctx) PostFormInt8(name string) (int8, error)

PostFormInt8 attempts to parse a int8 from PostForm value by name.

func (*Ctx) PostFormInt16 added in v0.1.33

func (c *Ctx) PostFormInt16(name string) (int16, error)

PostFormInt16 attempts to parse a int16 from PostForm value by name.

func (*Ctx) PostFormInt32 added in v0.1.33

func (c *Ctx) PostFormInt32(name string) (int32, error)

PostFormInt32 attempts to parse a int32 from PostForm value by name.

func (*Ctx) PostFormInt64 added in v0.1.33

func (c *Ctx) PostFormInt64(name string) (int64, error)

PostFormInt64 attempts to parse a int64 from PostForm value by name.

func (*Ctx) PostFormUint added in v0.1.33

func (c *Ctx) PostFormUint(name string) (uint, error)

PostFormUint attempts to parse a uint from PostForm value by name.

func (*Ctx) PostFormUint8 added in v0.1.33

func (c *Ctx) PostFormUint8(name string) (uint8, error)

PostFormUint8 attempts to parse a uint8 from PostForm value by name.

func (*Ctx) PostFormUint16 added in v0.1.33

func (c *Ctx) PostFormUint16(name string) (uint16, error)

PostFormUint16 attempts to parse a uint16 from PostForm value by name.

func (*Ctx) PostFormUint32 added in v0.1.33

func (c *Ctx) PostFormUint32(name string) (uint32, error)

PostFormUint32 attempts to parse a uint32 from PostForm value by name.

func (*Ctx) PostFormUint64 added in v0.1.33

func (c *Ctx) PostFormUint64(name string) (uint64, error)

PostFormUint64 attempts to parse a uint64 from PostForm value by name.

func (*Ctx) Push added in v0.1.34

func (c *Ctx) Push(target string, opts *http.PushOptions) error

Push implements http.Pusher when supported by the underlying writer.

func (*Ctx) Query added in v0.1.12

func (c *Ctx) Query(name string) string

Query retrieves a query string parameter by name from the request URL.

func (*Ctx) QueryBool added in v0.1.13

func (c *Ctx) QueryBool(name string) (bool, error)

QueryBool attempts to parse a bool from the request URL by name.

func (*Ctx) QueryFloat32 added in v0.1.13

func (c *Ctx) QueryFloat32(name string) (float32, error)

QueryFloat32 attempts to parse a float32 from the request URL by name.

func (*Ctx) QueryFloat64 added in v0.1.13

func (c *Ctx) QueryFloat64(name string) (float64, error)

QueryFloat64 attempts to parse a float64 from the request URL by name.

func (*Ctx) QueryInt added in v0.1.13

func (c *Ctx) QueryInt(name string) (int, error)

QueryInt attempts to parse a int from the request URL by name.

func (*Ctx) QueryInt8 added in v0.1.13

func (c *Ctx) QueryInt8(name string) (int8, error)

QueryInt8 attempts to parse a int8 from the request URL by name.

func (*Ctx) QueryInt16 added in v0.1.13

func (c *Ctx) QueryInt16(name string) (int16, error)

QueryInt16 attempts to parse a int16 from the request URL by name.

func (*Ctx) QueryInt32 added in v0.1.13

func (c *Ctx) QueryInt32(name string) (int32, error)

QueryInt32 attempts to parse a int32 from the request URL by name.

func (*Ctx) QueryInt64 added in v0.1.13

func (c *Ctx) QueryInt64(name string) (int64, error)

QueryInt64 attempts to parse a int64 from the request URL by name.

func (*Ctx) QueryUint added in v0.1.13

func (c *Ctx) QueryUint(name string) (uint, error)

QueryUint attempts to parse a uint from the request URL by name.

func (*Ctx) QueryUint8 added in v0.1.13

func (c *Ctx) QueryUint8(name string) (uint8, error)

QueryUint8 attempts to parse a uint8 from the request URL by name.

func (*Ctx) QueryUint16 added in v0.1.13

func (c *Ctx) QueryUint16(name string) (uint16, error)

QueryUint16 attempts to parse a uint16 from the request URL by name.

func (*Ctx) QueryUint32 added in v0.1.13

func (c *Ctx) QueryUint32(name string) (uint32, error)

QueryUint32 attempts to parse a uint32 from the request URL by name.

func (*Ctx) QueryUint64 added in v0.1.13

func (c *Ctx) QueryUint64(name string) (uint64, error)

QueryUint64 attempts to parse a uint64 from the request URL by name.

func (*Ctx) QueryValues added in v0.1.33

func (c *Ctx) QueryValues() url.Values

func (*Ctx) RemoteAddr added in v0.1.12

func (c *Ctx) RemoteAddr() string

RemoteAddr returns the remote IP address of the client making the request.

func (*Ctx) Request added in v0.1.33

func (c *Ctx) Request() *http.Request

func (*Ctx) RequestID added in v0.1.35

func (c *Ctx) RequestID() string

RequestID returns the request ID injected into the request context by RequestID middleware.

func (*Ctx) ResponseWriter added in v0.1.33

func (c *Ctx) ResponseWriter() http.ResponseWriter

func (*Ctx) SetCacheControl added in v0.1.32

func (c *Ctx) SetCacheControl(val string)

SetCacheControl Set Cache-Control to header

func (*Ctx) SetConnection added in v0.1.32

func (c *Ctx) SetConnection(val string)

SetConnection Set Connection to header

func (*Ctx) SetContentType added in v0.1.12

func (c *Ctx) SetContentType(val string)

SetContentType Set Content-Type to header

func (*Ctx) SetCookie added in v0.1.31

func (c *Ctx) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the provided [ResponseWriter]'s headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

func (*Ctx) SetHeader added in v0.1.34

func (c *Ctx) SetHeader(key string, value string)

SetHeader set header, short hand of w.Header().Set

func (*Ctx) SetOrigin added in v0.1.19

func (c *Ctx) SetOrigin(origin string)

SetOrigin sets the "Access-Control-Allow-Origin" header in the response.

func (*Ctx) SetStatus added in v0.1.36

func (c *Ctx) SetStatus(statusCode int)

SetStatus sets the response status code for framework-managed writes without immediately committing the response.

func (*Ctx) SetVersion added in v0.1.21

func (c *Ctx) SetVersion(version string)

SetVersion set `version` header

func (*Ctx) TryParseBody added in v0.1.12

func (c *Ctx) TryParseBody(val any) error

TryParseBody attempts to parse the request body based on its Content-Type and decode it into the provided value.

func (*Ctx) TryParseForm added in v0.1.12

func (c *Ctx) TryParseForm(name string, val any) error

TryParseForm attempts to parse a form value by name.

func (*Ctx) TryParseJSONBodyFast added in v0.1.35

func (c *Ctx) TryParseJSONBodyFast(val any) error

TryParseJSONBodyFast parses a JSON request body using a pooled buffer and json.Unmarshal. This is faster than TryParseBody for common JSON payloads, but unlike TryParseBody it does not reject unknown fields.

func (*Ctx) TryParseParam added in v0.1.12

func (c *Ctx) TryParseParam(name string, val any) error

TryParseParam attempts to parse a parameter value from the URL parameters.

func (*Ctx) TryParseQuery added in v0.1.12

func (c *Ctx) TryParseQuery(name string, val any) error

TryParseQuery attempts to parse a query string parameter value.

func (*Ctx) UserAgent added in v0.1.12

func (c *Ctx) UserAgent() string

UserAgent returns the User-Agent header from the request.

func (*Ctx) UserId added in v0.1.33

func (c *Ctx) UserId() uint64

UserId returns the user id from the context.

func (*Ctx) Write added in v0.1.12

func (c *Ctx) Write(p []byte) (int, error)

Write implements http.ResponseWriter and proxies to the underlying writer.

func (*Ctx) WriteHeader added in v0.1.34

func (c *Ctx) WriteHeader(statusCode int)

WriteHeader implements http.ResponseWriter and proxies to the underlying writer.

type ErrorBody added in v0.1.35

type ErrorBody struct {
	Code      int    `json:"code" xml:"code"`
	Message   string `json:"message" xml:"message"`
	RequestID string `json:"request_id,omitempty" xml:"request_id,omitempty"`
}

ErrorBody is a structured API error payload for opt-in error handlers.

type ErrorHandler added in v0.1.35

type ErrorHandler func(c *Ctx, err error) error

ErrorHandler handles a route error. Returning nil means the error was fully handled. Returning a non-nil error delegates to the framework default error writer.

func JSONErrorHandler added in v0.1.35

func JSONErrorHandler(includeRequestID bool) ErrorHandler

JSONErrorHandler returns an ErrorHandler that writes a structured JSON error body. This is opt-in and does not affect the framework's default error semantics.

type Fn added in v0.1.33

type Fn func(w http.ResponseWriter, r *http.Request) error

Fn

type IRelease added in v0.1.14

type IRelease interface {
	Release()
}

IRelease

type Middleware added in v0.1.12

type Middleware func(Next) Next

Middleware

func AccessLog added in v0.1.35

func AccessLog(fn func(c *Ctx, status int, d time.Duration, err error)) Middleware

AccessLog calls fn after request handling with an inferred status code and duration. The inferred status matches the framework's default success/error semantics.

func AccessLogWithOptions added in v0.1.35

func AccessLogWithOptions(opts AccessLogOptions) Middleware

AccessLogWithOptions calls opts.Log after request handling with an inferred status code and duration.

func Recover added in v0.1.35

func Recover(handler func(c *Ctx, recovered any) error) Middleware

Recover converts panics in downstream middleware/handlers into framework errors. If handler is nil, a default 500 JSON response is produced. If handler returns nil, the panic is assumed to have been fully handled.

func RecoverWithOptions added in v0.1.35

func RecoverWithOptions(opts RecoverOptions) Middleware

RecoverWithOptions converts panics in downstream middleware/handlers into framework errors.

func RequestID added in v0.1.35

func RequestID(header string, nextID func() string) Middleware

RequestID injects a request ID into the request context and response headers. If the incoming request already contains the header, it is preserved. When nextID is nil, a compact monotonic ID is generated.

func Timeout added in v0.1.35

func Timeout(d time.Duration) Middleware

Timeout applies a cooperative deadline to request processing. Handlers that observe c.Context() can stop work early and return promptly.

type Next added in v0.1.22

type Next func(c *Ctx) (any, error)

Next

type Panic added in v0.1.22

type Panic func(http.ResponseWriter, *http.Request, any)

Panic

type Param

type Param struct {
	Key   string
	Value string
}

Param struct

type Params

type Params []Param

Params list

func (*Params) Val

func (o *Params) Val(name string) string

Val get value from Params by name

type RawBody added in v0.1.35

type RawBody []byte

RawBody is an explicit opt-in container for raw HTTP response bytes. It bypasses JSON decoding in client helpers.

type Reader

type Reader func(c *Ctx, v any) error

Reader

type RecoverOptions added in v0.1.35

type RecoverOptions struct {
	Handler       func(c *Ctx, recovered any) error
	DefaultStatus int
	DefaultBody   string
}

RecoverOptions configures panic recovery middleware behavior.

type RouteGroup added in v0.1.35

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

RouteGroup groups routes under a shared path prefix and middleware chain.

func (*RouteGroup) Delete added in v0.1.35

func (g *RouteGroup) Delete(path string, next Next)

Delete registers a DELETE route on the group.

func (*RouteGroup) Get added in v0.1.35

func (g *RouteGroup) Get(path string, next Next)

Get registers a GET route on the group.

func (*RouteGroup) Group added in v0.1.35

func (g *RouteGroup) Group(prefix string, middleware ...Middleware) *RouteGroup

Group creates a nested route group.

func (*RouteGroup) Handle added in v0.1.35

func (g *RouteGroup) Handle(method string, path string, next Next, middleware ...Middleware)

Handle registers a route on the group.

func (*RouteGroup) Head added in v0.1.35

func (g *RouteGroup) Head(path string, next Next)

Head registers a HEAD route on the group.

func (*RouteGroup) Options added in v0.1.35

func (g *RouteGroup) Options(path string, next Next)

Options registers an OPTIONS route on the group.

func (*RouteGroup) Patch added in v0.1.35

func (g *RouteGroup) Patch(path string, next Next)

Patch registers a PATCH route on the group.

func (*RouteGroup) Post added in v0.1.35

func (g *RouteGroup) Post(path string, next Next)

Post registers a POST route on the group.

func (*RouteGroup) Put added in v0.1.35

func (g *RouteGroup) Put(path string, next Next)

Put registers a PUT route on the group.

func (*RouteGroup) Use added in v0.1.35

func (g *RouteGroup) Use(middleware ...Middleware)

Use appends middleware to the group.

type Writer

type Writer func(c *Ctx, v any) error

Writer

Jump to

Keyboard shortcuts

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