Documentation
¶
Index ¶
- Constants
- func NewHTTPError(code int, message string, detail ...any) error
- type App
- func (a *App) DELETE(path string, handlers ...Handler)
- func (a *App) GET(path string, handlers ...Handler)
- func (a *App) Health(livenessPath, readinessPath string, ready func() bool)
- func (a *App) ListRoutes() []RouteInfo
- func (a *App) PATCH(path string, handlers ...Handler)
- func (a *App) POST(path string, handlers ...Handler)
- func (a *App) PUT(path string, handlers ...Handler)
- func (a *App) Plug(m ...Handler)
- func (a *App) PrintRoutes(w io.Writer)
- func (a *App) Run(addr string) error
- func (a *App) Scope(prefix string, mws ...Handler) *Scope
- func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *App) ServeSwagger(path string, options ...func(*httpSwagger.Config)) *App
- func (a *App) SetNotFound(h Handler) *App
- func (a *App) SetOnPanic(fn func(*Context, any)) *App
- func (a *App) SetOnRequest(fn func(*Context)) *App
- func (a *App) SetOnResponse(fn func(*Context, int, time.Duration)) *App
- func (a *App) SetPrintRoutes(v bool) *App
- func (a *App) SetVersion(v string) *App
- func (a *App) Shutdown(ctx context.Context, srv *http.Server) error
- func (a *App) Start(cfg *ServerConfig) (*http.Server, error)
- func (a *App) StartTLS(cfg *ServerConfig, certFile, keyFile string) (*http.Server, error)
- func (a *App) Static(prefix string, opt StaticOptions)
- func (a *App) Version() string
- type Context
- func (c *Context) Abort()
- func (c *Context) Aborted() bool
- func (c *Context) Accepts(candidates ...string) string
- func (c *Context) BindFormInto(dst any) error
- func (c *Context) BindHeaderInto(dst any) error
- func (c *Context) BindInto(dst any) error
- func (c *Context) BindJSONInto(dst any) error
- func (c *Context) BindPathInto(dst any) error
- func (c *Context) BindQueryInto(dst any) error
- func (c *Context) ClearError()
- func (c *Context) Data(code int, contentType string, b []byte)
- func (c *Context) Deadline() (time.Time, bool)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Download(filepath string, filename string)
- func (c *Context) Err() error
- func (c *Context) Error() error
- func (c *Context) Fail(code int, message string, detail ...any)
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) GetHeader(key string) string
- func (c *Context) HTML(code int, html string)
- func (c *Context) JSON(code int, v any)
- func (c *Context) Negotiate(code int, candidates map[string]any)
- func (c *Context) Next()
- func (c *Context) Param(key string) string
- func (c *Context) Problem(status int, typeURI, title, detail, instance string, ext map[string]any)
- func (c *Context) Problemf(status int, title string, detail string)
- func (c *Context) PushSSE(fn func(event func(name, data string)))
- func (c *Context) PushStream(fn func(w io.Writer, flush func()))
- func (c *Context) Query(key string) string
- func (c *Context) RealIP() string
- func (c *Context) RequestID() string
- func (c *Context) SaveUploadedFile(field, dstDir string, opt UploadOptions) (string, error)
- func (c *Context) SendAttachment(path, filename string)
- func (c *Context) SendBytes(code int, b []byte)
- func (c *Context) SendStatus(code int)
- func (c *Context) Set(key string, v any)
- func (c *Context) SetError(err error)
- func (c *Context) SetHeader(k, v string)
- func (c *Context) String(code int, format string, values ...any)
- func (c *Context) UploadedFile(field string, maxMemory int64) (multipart.File, *multipart.FileHeader, error)
- func (c *Context) Value(key any) any
- func (c *Context) XML(code int, v any)
- type HTTPError
- type Handler
- type Problem
- type RouteInfo
- type Scope
- func (s *Scope) DELETE(path string, handlers ...Handler)
- func (s *Scope) GET(path string, handlers ...Handler)
- func (s *Scope) PATCH(path string, handlers ...Handler)
- func (s *Scope) POST(path string, handlers ...Handler)
- func (s *Scope) PUT(path string, handlers ...Handler)
- func (s *Scope) Scope(prefix string, mws ...Handler) *Scope
- func (s *Scope) Use(middlewares ...Handler)
- type ServerConfig
- type StaticOptions
- type UploadOptions
Constants ¶
const ( AppVersion = "app_version" RequestID = "request_id" XRequestID = "X-Request-ID" TraceParent = "traceparent" TraceID = "trace_id" SpanID = "span_id" )
Variables ¶
This section is empty.
Functions ¶
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the main entrypoint of the framework.
func (*App) Health ¶
Health mounts tiny health endpoints onto the current App. - If livenessPath is non-empty, it returns 200 when the process is alive. - If readinessPath is non-empty and ready != nil, it returns 200/503 based on ready().
func (*App) ListRoutes ¶
Get route list (copy & sort for stability)
func (*App) PrintRoutes ¶
func (*App) Run ¶
Run keeps backward compatibility: starts a blocking server with production-leaning defaults. Equivalent to ListenAndServe.
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP uses a context pool and the precompiled router to handle the request.
func (*App) ServeSwagger ¶
func (a *App) ServeSwagger(path string, options ...func(*httpSwagger.Config)) *App
ServeSwagger mounts Swagger UI at the specified path This is a convenience method that automatically sets up the route
Usage:
app.ServeSwagger("/swagger")
// Now accessible at: http://localhost:8000/swagger/index.html
func (*App) SetNotFound ¶
SetNotFound sets a custom 404 handler hook.
func (*App) SetOnPanic ¶
SetOnPanic registers a hook called when a panic occurs. The panic value is forwarded and will be re-panicked after the hook returns.
func (*App) SetOnRequest ¶
SetOnRequest registers a hook called at the start of handling a request.
func (*App) SetOnResponse ¶
SetOnResponse registers a hook called after the request is handled. Parameters: (ctx, statusCode, latency).
func (*App) SetPrintRoutes ¶
Enable/disable route printing when server starts
func (*App) SetVersion ¶
SetVersion configures an application version string injected per request.
func (*App) Shutdown ¶
Shutdown requests a graceful stop. The server stops accepting new connections and waits for in-flight requests until ctx is done.
func (*App) Start ¶
func (a *App) Start(cfg *ServerConfig) (*http.Server, error)
Start starts the server in a new goroutine and returns *http.Server. This is recommended in production to manage lifecycle explicitly.
func (*App) Static ¶
func (a *App) Static(prefix string, opt StaticOptions)
Static mounts a read-only file server under a prefix. It sets ETag and Last-Modified, and handles If-None-Match / If-Modified-Since. Security notes: - Prevents path traversal ("..") by cleaning and validating joined path. - Optional extension allow-list (if non-empty).
type Context ¶
type Context struct {
Writer http.ResponseWriter
Request *http.Request
// contains filtered or unexported fields
}
Context carries request-scoped values and the middleware/handler chain.
func (*Context) Accepts ¶
Accepts returns the preferred type among provided candidates according to the request's "Accept" header. It returns the first element of candidates if the header is empty or no match is found.
func (*Context) BindFormInto ¶
BindFormInto binds form data into dst and validates tags.
func (*Context) BindHeaderInto ¶
BindHeaderInto maps request headers into a struct. Tag: `header:"X-Trace-Id,required"` ; if no tag -> use Canonical(FieldName).
func (*Context) BindInto ¶
Binding & Validation BindInto auto-detects the binder (JSON/Form/Query), binds into dst, then validates tags.
func (*Context) BindJSONInto ¶
BindJSONInto binds JSON into dst and validates tags.
func (*Context) BindPathInto ¶
BindPathInto maps path params (zentrox params) into a struct. Tag: `path:"id,required"` ; if no tag -> use lowerCamel(FldName).
func (*Context) BindQueryInto ¶
BindQueryInto binds query params into dst and validates tags.
func (*Context) ClearError ¶
func (c *Context) ClearError()
ClearError clears the last recorded error.
func (*Context) Deadline ¶
Deadline returns the time when work done on behalf of this request should be canceled. It proxies http.Request.Context().
func (*Context) Done ¶
func (c *Context) Done() <-chan struct{}
Done returns a channel that is closed when the request context is canceled. It proxies http.Request.Context().
func (*Context) Err ¶
Err reports why the request context was canceled, if it was. It proxies http.Request.Context().
func (*Context) Negotiate ¶
Negotiate writes the response based on the request's Accept header. candidates is a map of content-type -> payload. Supported types out-of-the-box:
- "application/json": payload marshaled as JSON (via SendJSON)
- "text/plain": payload must be string
- "text/html": payload must be string (HTML)
- "application/xml": payload marshaled as XML (via SendXML)
Example:
c.Negotiate(200, map[string]any{
"application/json": obj,
"text/plain": "hello",
})
func (*Context) Next ¶
func (c *Context) Next()
Next executes the next handler in the middleware chain
func (*Context) Problem ¶
Problem writes an application/problem+json response using the provided fields. The Content-Type is set to "application/problem+json".
func (*Context) Problemf ¶
Problemf is a convenience helper to write a simple problem without instance/ext.
func (*Context) PushStream ¶
func (*Context) RealIP ¶
RealIP returns the client IP considering common reverse proxy headers. Order: X-Forwarded-For (first), X-Real-IP, then RemoteAddr fallback.
func (*Context) RequestID ¶
RequestID returns the request ID if a RequestID middleware has stored it.
func (*Context) SaveUploadedFile ¶
func (c *Context) SaveUploadedFile(field, dstDir string, opt UploadOptions) (string, error)
SaveUploadedFile reads file from multipart form by field name and writes it into dstDir. It validates extension (if provided), prevents path traversal, and can sanitize/generate names. Returns the full path saved to.
func (*Context) SendAttachment ¶
func (*Context) SendStatus ¶
func (*Context) SetError ¶
SetError records an error for the request (ErrorHandler can render it later).
func (*Context) UploadedFile ¶
func (c *Context) UploadedFile(field string, maxMemory int64) (multipart.File, *multipart.FileHeader, error)
UploadedFile returns the multipart file and header for advanced use. Caller must close the returned multipart.File.
type HTTPError ¶
type HTTPError struct {
Code int `json:"code"`
Message string `json:"message"`
Detail any `json:"detail,omitempty"`
}
HTTPError is the canonical error payload returned by the framework.
type Handler ¶
type Handler func(*Context)
Handler is the middleware/handler function type.
func SwaggerHandler ¶
func SwaggerHandler(options ...func(*httpSwagger.Config)) Handler
SwaggerHandler returns a handler that serves Swagger UI
Usage:
app.GET("/swagger/*any", zentrox.SwaggerHandler())
Or with custom config:
app.GET("/swagger/*any", zentrox.SwaggerHandler(
httpSwagger.URL("http://localhost:8000/swagger/doc.json"),
))
func SwaggerJSON ¶
func SwaggerJSON() Handler
SwaggerJSON serves the raw swagger.json file Useful if you want to expose the OpenAPI spec separately
Usage:
app.GET("/swagger.json", zentrox.SwaggerJSON())
func SwaggerYAML ¶
func SwaggerYAML() Handler
SwaggerYAML serves the raw swagger.yaml file
Usage:
app.GET("/swagger.yaml", zentrox.SwaggerYAML())
type Problem ¶
type Problem struct {
Type string `json:"type,omitempty"` // A URI reference that identifies the problem type
Title string `json:"title,omitempty"` // A short, human-readable summary of the problem type
Status int `json:"status,omitempty"` // HTTP status code generated by the origin server
Detail string `json:"detail,omitempty"` // Human-readable explanation specific to this occurrence
Instance string `json:"instance,omitempty"` // A URI reference that identifies the specific occurrence
Ext map[string]any `json:"-"` // extension members
}
Problem is a serializable RFC 9457 error object. Extension members are included when marshaled by merging Ext into the base object.
func (Problem) MarshalJSON ¶
MarshalJSON merges extension members into the base JSON.
type Scope ¶
type Scope struct {
// contains filtered or unexported fields
}
Scope (Route Group)
type ServerConfig ¶
type ServerConfig struct {
// Address to listen on, e.g. ":8000".
Addr string
// Timeouts protect the server from slow or stuck clients.
// Defaults: ReadHeader=5s, Read=15s, Write=30s, Idle=60s.
ReadHeaderTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
// Upper bound for request headers (default 1 MiB).
MaxHeaderBytes int
// Where to write internal http.Server logs.
// Default: stderr with prefix "zentrox/http: ".
ErrorLog *log.Logger
// BaseContext sets the base context for all connections (optional).
BaseContext func(net.Listener) context.Context
}
ServerConfig controls the underlying http.Server configuration. All fields are optional; sensible defaults are applied.
type StaticOptions ¶
type StaticOptions struct {
// Directory on disk to serve from (absolute or relative to process cwd).
Dir string
// Optional index filename to serve when requesting the prefix root (e.g. "index.html").
Index string
// If true, do not auto-serve index when the request equals the prefix.
DisableIndex bool
// If non-zero, sets "Cache-Control: public, max-age=<seconds>" (otherwise no-cache).
MaxAge time.Duration
// If true, use strong ETag (SHA1 of content). Otherwise weak ETag (size-modtime).
UseStrongETag bool
// Optional allow-list of file extensions (lowercase, with dot), e.g. []string{".css",".js",".png"}.
AllowedExt []string
}
StaticOptions controls behavior of Static(...)
type UploadOptions ¶
type UploadOptions struct {
// Maximum memory used by ParseMultipartForm; files larger than this are stored in temporary files.
MaxMemory int64 // default 10 << 20 (10 MiB)
// Allowed file extensions (lowercase, with dot). Empty means allow all.
AllowedExt []string
// If true, sanitize the base filename (only [a-zA-Z0-9._-]) to avoid weird characters.
Sanitize bool
// If true, always generate a unique filename (timestamp + random suffix).
GenerateUniqueName bool
// If false and file exists, returns error. If true, overwrite existing file.
Overwrite bool
}
UploadOptions controls how files are accepted and saved.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
auth
command
|
|
|
basic
command
|
|
|
binding
command
|
|
|
custom_middleware
command
|
|
|
enterprise
command
|
|
|
graceful
command
|
|
|
gzip
command
|
|
|
jwt_custom
command
|
|
|
middleware
command
|
|
|
minimal
command
|
|
|
rendering
command
|
|
|
swagger_annotations
command
|
|
|
swagger_annotations/docs
Package docs Code generated by swaggo/swag.
|
Package docs Code generated by swaggo/swag. |
|
use_middleware
command
|
|
