web

package
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: Apache-2.0 Imports: 39 Imported by: 1

Documentation

Overview

Package web: server configuration types and defaults.

Package web: response converter that transforms handler results to HTTP responses.

Package web: cookie helper for reading and writing HTTP cookies.

Package web: error code constants and structured error types.

Package web: file download and static file system response types.

Package web: filter chain for request processing middleware.

Package web: route collection that can be transferred to a Server.

Package web: key-value map type with type-safe accessors.

Package web: in-memory filesystem for serving static files.

Package web: standard response message format with code, data, msg, and type.

Package web: reverse proxy handler.

Package web: HTTP request wrapper with helper methods for params, query, JSON binding.

Package web: HTTP response interface for writing JSON, files, redirects.

Package web: route definition, handler metadata, and meta options.

Package web: server runner that manages HTTP/TLS listeners and auto-cert.

Package web: HTTP server with routing, filters, and static file support.

Package web: Server-Sent Events stream support.

Package web: TLS certificate store and auto-certification.

Package web: WebSocket stream support.

Index

Constants

View Source
const (
	CodeOK                 = 200
	CodeBadRequest         = 400
	CodeUnauthorized       = 401
	CodeForbidden          = 403
	CodeNotFound           = 404
	CodeMethodNotAllowed   = 405
	CodeTooManyRequests    = 429
	CodeInternalError      = 500
	CodeServiceUnavailable = 503
	// Business error codes (1000+)
	CodeValidationFailed = 1001
	CodeDuplicateEntry   = 1002
	CodeTokenExpired     = 1003
	CodeTokenInvalid     = 1004
)

Error code constants

View Source
const DefaultMaxBodySize int64 = 10 << 20

DefaultMaxBodySize is the default maximum request body size (10 MB).

View Source
const GetNotSupportJson = "JSON parameters are not supported in GET requests"

GetNotSupportJson is the error message returned when a GET request attempts to bind JSON parameters.

View Source
const MaxHeaderBytes = 8192

MaxHeaderBytes is the maximum size of request headers in bytes.

View Source
const MaxReadHeaderTimeout = time.Second * 30

MaxReadHeaderTimeout is the maximum duration for reading request headers.

View Source
const MaxReadTimeout = time.Minute * 10

MaxReadTimeout is the maximum duration for reading the entire request.

View Source
const ServerConfigKey = "web.server"

ServerConfigKey is the configuration key for server settings.

Variables

View Source
var (
	ErrBadRequest         = NewErrorCode(CodeBadRequest, "bad request")
	ErrUnauthorized       = NewErrorCode(CodeUnauthorized, "unauthorized")
	ErrForbidden          = NewErrorCode(CodeForbidden, "forbidden")
	ErrNotFound           = NewErrorCode(CodeNotFound, "not found")
	ErrMethodNotAllowed   = NewErrorCode(CodeMethodNotAllowed, "method not allowed")
	ErrTooManyRequests    = NewErrorCode(CodeTooManyRequests, "too many requests")
	ErrInternalError      = NewErrorCode(CodeInternalError, "internal server error")
	ErrServiceUnavailable = NewErrorCode(CodeServiceUnavailable, "service unavailable")
	ErrValidationFailed   = NewErrorCode(CodeValidationFailed, "validation failed")
	ErrDuplicateEntry     = NewErrorCode(CodeDuplicateEntry, "duplicate entry")
	ErrTokenExpired       = NewErrorCode(CodeTokenExpired, "token expired")
	ErrTokenInvalid       = NewErrorCode(CodeTokenInvalid, "token invalid")
)

Pre-defined ErrorCode instances. Use with errors.Is/As or pass to Error().

Functions

func ClassifyError added in v1.0.8

func ClassifyError(value any, err error) (int, string)

ClassifyError maps an error to an HTTP status code and message string.

func SaveUploadedFile added in v0.1.3

func SaveUploadedFile(file *multipart.FileHeader, dst string) error

SaveUploadedFile saves an uploaded file to the destination path. It creates the destination directory if it does not exist.

Types

type AcceptOptions added in v1.0.13

type AcceptOptions func(*acceptOptions)

func WithCompressionMode added in v1.0.13

func WithCompressionMode(mode int) AcceptOptions

WithCompressionMode sets the WebSocket compression mode. Use CompressionDisabled, CompressionNoContextTakeover, or CompressionContextTakeover.

func WithCompressionThreshold added in v1.0.13

func WithCompressionThreshold(threshold int) AcceptOptions

WithCompressionThreshold sets the minimum message size before compression is applied.

func WithInsecureSkipVerify added in v1.0.13

func WithInsecureSkipVerify(skip bool) AcceptOptions

WithInsecureSkipVerify disables origin verification during WebSocket Accept.

func WithOnPingReceived added in v1.0.13

func WithOnPingReceived(fn func(ctx context.Context, payload []byte) bool) AcceptOptions

WithOnPingReceived sets a callback invoked when a ping frame is received. Return false to suppress the automatic pong response.

func WithOnPongReceived added in v1.0.13

func WithOnPongReceived(fn func(ctx context.Context, payload []byte)) AcceptOptions

WithOnPongReceived sets a callback invoked when a pong frame is received.

func WithOriginPatterns added in v1.0.13

func WithOriginPatterns(OriginPatterns []string) AcceptOptions

func WithSubprotocols added in v1.0.13

func WithSubprotocols(subprotocols ...string) AcceptOptions

WithSubprotocols sets the WebSocket subprotocols to negotiate during Accept.

type Converter added in v0.1.3

type Converter interface {
	// Request converts the handler result to an HTTP response.
	Request(filterChain FilterChain, request *Request)
}

Converter transforms handler return values into HTTP responses. It is called after the filter chain completes.

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

Cookie provides helper methods for reading, writing, and deleting HTTP cookies.

func NewCookie

func NewCookie(c *gin.Context) *Cookie

NewCookie creates a new Cookie helper for the given context.

func (*Cookie) Delete

func (c *Cookie) Delete(key string)

Delete removes a cookie by setting its expiration to the past.

func (*Cookie) Expire

func (c *Cookie) Expire(key string)

Expire removes a cookie by setting its expiration to the past.

func (*Cookie) Forever

func (c *Cookie) Forever(key string, value string, opts ...CookieOption)

Forever sets a session cookie (MaxAge=0, expires when browser closes).

func (*Cookie) ForeverDomain

func (c *Cookie) ForeverDomain(domain string, key string, value string, opts ...CookieOption)

ForeverDomain sets a session cookie scoped to a specific domain.

func (*Cookie) Get

func (c *Cookie) Get(key string) string

Get returns the value of a cookie by key, or empty string if not found.

func (*Cookie) Set

func (c *Cookie) Set(key string, value string, opts ...CookieOption)

Set sets a cookie with optional custom attributes. Defaults (no options): MaxAge=1 year, Path="/", HttpOnly=false, Secure=false (backward compatible).

cookie.Set("token", value)                              // backward compatible defaults
cookie.Set("token", value, WithSecure(true))            // HTTPS only
cookie.Set("token", value, WithHttpOnly(true), WithSameSite(http.SameSiteLaxMode))

func (*Cookie) SetDomain

func (c *Cookie) SetDomain(domain string, key string, value string, opts ...CookieOption)

SetDomain sets a cookie scoped to a specific domain.

func (*Cookie) SetWithExpire

func (c *Cookie) SetWithExpire(key string, value string, expire int, opts ...CookieOption)

SetWithExpire sets a cookie with a custom max-age in seconds.

func (*Cookie) Update

func (c *Cookie) Update(key string, value string)

Update updates a cookie value with default options.

type CookieOption added in v1.0.4

type CookieOption func(*http.Cookie)

CookieOption is a functional option for configuring cookie attributes.

func WithDomain added in v1.0.4

func WithDomain(domain string) CookieOption

WithDomain sets the cookie domain.

func WithHttpOnly added in v1.0.4

func WithHttpOnly(httpOnly bool) CookieOption

WithHttpOnly sets the HttpOnly flag (not accessible via JavaScript).

func WithPath added in v1.0.4

func WithPath(path string) CookieOption

WithPath sets the cookie path.

func WithSameSite added in v1.0.4

func WithSameSite(sameSite http.SameSite) CookieOption

WithSameSite sets the SameSite attribute.

func WithSecure added in v1.0.4

func WithSecure(secure bool) CookieOption

WithSecure sets the Secure flag (only send over HTTPS).

type DefaultConverter added in v0.1.3

type DefaultConverter struct {
}

DefaultConverter is the built-in converter that handles Message, string, *FileResponse, *os.File, and arbitrary values (converted to JSON).

func (*DefaultConverter) Error added in v1.0.4

func (c *DefaultConverter) Error(request *Request, value any, err error)

Error writes an error response and aborts the request. It recognizes *ErrorCode, *Message, os sentinel errors, and maps them to appropriate HTTP status codes.

func (*DefaultConverter) FileResponse added in v1.0.4

func (c *DefaultConverter) FileResponse(request *Request, value *FileResponse)

FileResponse sends a file attachment response to the client.

func (*DefaultConverter) FileSystemResponse added in v1.0.4

func (c *DefaultConverter) FileSystemResponse(request *Request, value *FileSystemResponse)

FileSystemResponse serves a file from an http.FileSystem.

func (*DefaultConverter) Message added in v1.0.4

func (c *DefaultConverter) Message(request *Request, value *Message)

Message writes a Message response, handling redirect and JSON cases.

func (*DefaultConverter) RawFile added in v1.0.4

func (c *DefaultConverter) RawFile(request *Request, value *os.File)

RawFile sends an os.File as an attachment response.

func (*DefaultConverter) Request added in v0.1.3

func (c *DefaultConverter) Request(filterChain FilterChain, request *Request)

Request converts the handler result to the appropriate HTTP response. It handles errors, Message, string, file download, and JSON responses.

func (*DefaultConverter) ReverseProxyResponse added in v1.0.4

func (c *DefaultConverter) ReverseProxyResponse(request *Request, value *ReverseProxyResponse)

ReverseProxyResponse forwards the request to the target URL as a reverse proxy.

func (*DefaultConverter) SSEResponse added in v1.0.4

func (c *DefaultConverter) SSEResponse(request *Request, value *SSEResponse)

SSEResponse sets up an SSE stream and invokes the handler.

func (*DefaultConverter) String added in v1.0.4

func (c *DefaultConverter) String(request *Request, value string)

String writes a plain text string to the response.

func (*DefaultConverter) WSResponse added in v1.0.4

func (c *DefaultConverter) WSResponse(request *Request, value *WSResponse)

WSResponse accepts a WebSocket upgrade and invokes the handler.

type ErrorCode added in v0.7.3

type ErrorCode struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Detail  string `json:"detail,omitempty"`
	Err     error  `json:"-"`
}

ErrorCode is a structured error that can be used as Message.Data.

func NewBadRequest added in v0.7.3

func NewBadRequest() *ErrorCode

NewBadRequest returns a new 400 Bad Request error (copy of ErrBadRequest).

func NewDuplicateEntry added in v0.7.3

func NewDuplicateEntry() *ErrorCode

NewDuplicateEntry returns a new 1002 Duplicate Entry error (copy of ErrDuplicateEntry).

func NewErrorCode added in v0.7.3

func NewErrorCode(code int, msg string) *ErrorCode

NewErrorCode creates a new ErrorCode with the given code and message.

func NewErrorCodeWithError added in v1.0.7

func NewErrorCodeWithError(code int, err error) *ErrorCode

NewErrorCodeWithError creates a new ErrorCode with the given code and wraps the original error.

func NewForbidden added in v0.7.3

func NewForbidden() *ErrorCode

NewForbidden returns a new 403 Forbidden error (copy of ErrForbidden).

func NewInternalError added in v0.7.3

func NewInternalError() *ErrorCode

NewInternalError returns a new 500 Internal Server Error error (copy of ErrInternalError).

func NewMethodNotAllowed added in v0.7.3

func NewMethodNotAllowed() *ErrorCode

NewMethodNotAllowed returns a new 405 Method Not Allowed error (copy of ErrMethodNotAllowed).

func NewNotFound added in v0.7.3

func NewNotFound() *ErrorCode

NewNotFound returns a new 404 Not Found error (copy of ErrNotFound).

func NewServiceUnavailable added in v0.7.3

func NewServiceUnavailable() *ErrorCode

NewServiceUnavailable returns a new 503 Service Unavailable error (copy of ErrServiceUnavailable).

func NewTokenExpired added in v0.7.3

func NewTokenExpired() *ErrorCode

NewTokenExpired returns a new 1003 Token Expired error (copy of ErrTokenExpired).

func NewTokenInvalid added in v0.7.3

func NewTokenInvalid() *ErrorCode

NewTokenInvalid returns a new 1004 Token Invalid error (copy of ErrTokenInvalid).

func NewTooManyRequests added in v0.7.3

func NewTooManyRequests() *ErrorCode

NewTooManyRequests returns a new 429 Too Many Requests error (copy of ErrTooManyRequests).

func NewUnauthorized added in v0.7.3

func NewUnauthorized() *ErrorCode

NewUnauthorized returns a new 401 Unauthorized error (copy of ErrUnauthorized).

func NewValidationError added in v0.7.3

func NewValidationError() *ErrorCode

NewValidationError returns a new 1001 Validation Failed error (copy of ErrValidationFailed).

func (*ErrorCode) Error added in v0.7.3

func (e *ErrorCode) Error() string

Error implements the error interface.

func (*ErrorCode) Unwrap added in v1.0.7

func (e *ErrorCode) Unwrap() error

Unwrap returns the wrapped error, supporting errors.Is/As chains.

func (*ErrorCode) WithDetail added in v0.7.3

func (e *ErrorCode) WithDetail(detail string) *ErrorCode

WithDetail attaches additional detail information to the ErrorCode.

func (*ErrorCode) WithError added in v1.0.7

func (e *ErrorCode) WithError(err error) *ErrorCode

WithError wraps the original error into the ErrorCode.

type FileResponse added in v1.0.4

type FileResponse struct {
	Path     string // File system path to the file
	FileName string // Name shown to the client on download
	Suffix   string // Optional suffix appended to the filename
}

File represents a downloadable file response. Path is the file system path, FileName is the download name, and Suffix is an optional suffix appended to the filename.

func CreateFileResponse added in v1.0.4

func CreateFileResponse(path string) *FileResponse

CreateFile creates a File from a path, auto-extracting the filename and suffix.

func CreateFileResponseWithName added in v1.0.4

func CreateFileResponseWithName(path string, fileName string) *FileResponse

CreateFileWithName creates a File from a path with a custom download filename.

type FileSystemResponse added in v1.0.4

type FileSystemResponse struct {
	Filepath string
	FS       http.FileSystem
}

FileSystemResponse serves a file from an embedded or in-memory http.FileSystem.

type Filter added in v0.1.3

type Filter interface {
	// Handle processes the request.
	// fc: the filter chain, used to invoke the next filter
	// request: the HTTP request object
	// Returns (any, error): the result and any error
	Handle(filterChain FilterChain, request *Request) (any, error)
}

Filter is a middleware that intercepts requests before and after the handler.

type FilterChain added in v0.1.3

type FilterChain interface {
	// Next executes the next filter or the final handler in the chain.
	// Returns (any, error): the result and any error.
	Next() (any, error)
}

FilterChain is a chain of filters and the final handler, invoked via Next.

type HandlerChain added in v1.0.4

type HandlerChain []HandlerFunc

HandlerChain is a chain of handler functions.

func (HandlerChain) GetFuncName added in v1.0.4

func (c HandlerChain) GetFuncName() string

GetFuncName returns the name of the last handler function in the chain.

func (HandlerChain) Last added in v1.0.4

func (c HandlerChain) Last() HandlerFunc

Last returns the last handler in the chain, or nil if the chain is empty.

type HandlerFunc

type HandlerFunc func(*Request) (any, error)

HandlerFunc is the function signature for request handlers.

type HandlerMeta added in v0.1.3

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

HandlerMeta holds key-value metadata attached to a route handler.

func NewHandlerMeta added in v0.1.3

func NewHandlerMeta() *HandlerMeta

NewHandlerMeta creates a new empty HandlerMeta.

func (*HandlerMeta) Add added in v0.1.3

func (hm *HandlerMeta) Add(key string, value any)

Add sets a key-value pair in the handler metadata.

func (*HandlerMeta) Get added in v0.1.3

func (hm *HandlerMeta) Get(key string) any

Get returns the value for the given key, or nil if not found.

func (*HandlerMeta) Has added in v0.1.3

func (hm *HandlerMeta) Has(key string) bool

Has reports whether the given key exists in the handler metadata.

type Handles added in v0.1.3

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

Handles collects route definitions before they are registered on a Server. Use NewHandles() to create, then register routes via Get/Post/etc, and finally call server.AddHandles(handles) to apply them.

func NewHandles added in v0.1.3

func NewHandles() *Handles

NewHandles creates a new empty Handles.

func (*Handles) AddReverseProxy added in v0.7.1

func (h *Handles) AddReverseProxy(relativePath string, target string) *Route

AddReverseProxy registers a reverse proxy to the target URL for all HTTP methods. The relativePath should be a prefix (e.g. "/api"); a wildcard is appended automatically so that "/api/hello" matches in addition to "/api".

func (*Handles) AddSSE added in v0.7.1

func (h *Handles) AddSSE(relativePath string, handler SSEHandler) *Route

AddSSE registers a Server-Sent Events endpoint.

func (*Handles) AddStaticFs added in v0.7.1

func (h *Handles) AddStaticFs(relativePath string, fs http.FileSystem) *Route

AddStaticFs registers a static file server at the given path.

func (*Handles) AddWebSocket added in v0.7.1

func (h *Handles) AddWebSocket(relativePath string, handler WebSocketHandler) *Route

AddWebSocket registers a WebSocket endpoint.

func (*Handles) Any added in v0.9.6

func (h *Handles) Any(relativePath string, handlers ...HandlerFunc) *Route

Any registers a route handler for all HTTP methods.

func (*Handles) Delete added in v1.0.4

func (h *Handles) Delete(relativePath string, handlers ...HandlerFunc) *Route

Delete registers a DELETE route handler.

func (*Handles) Empty added in v0.7.1

func (h *Handles) Empty() bool

Empty reports whether no routes have been registered.

func (*Handles) Get added in v1.0.4

func (h *Handles) Get(relativePath string, handlers ...HandlerFunc) *Route

Get registers a GET route handler.

func (*Handles) Handle added in v0.1.3

func (h *Handles) Handle(httpMethod string, relativePath string, handlers ...HandlerFunc) *Route

Handle registers a handler for a single HTTP method.

func (*Handles) Handlers added in v1.0.4

func (h *Handles) Handlers(httpMethods []string, relativePath string, handlers ...HandlerFunc) *Route

Handlers registers a handler for multiple HTTP methods.

func (*Handles) Patch added in v1.0.4

func (h *Handles) Patch(relativePath string, handlers ...HandlerFunc) *Route

Patch registers a PATCH route handler.

func (*Handles) Post added in v1.0.4

func (h *Handles) Post(relativePath string, handlers ...HandlerFunc) *Route

Post registers a POST route handler.

func (*Handles) Put added in v1.0.4

func (h *Handles) Put(relativePath string, handlers ...HandlerFunc) *Route

Put registers a PUT route handler.

type JSONObject added in v1.0.4

type JSONObject = KV

JSONObject is a convenience type for working with JSON objects as maps. It is an alias for KV, inheriting all helper methods (GetString, GetInt, etc.).

type KV added in v1.0.4

type KV map[string]any

KV is a string-keyed map with type-safe accessor methods.

func (KV) Add added in v1.0.4

func (o KV) Add(key string, value any)

Add sets the value for key in the KV.

func (KV) GetArray added in v1.0.12

func (o KV) GetArray(key string) []any

GetArray returns the value for key as a slice, or nil.

func (KV) GetBool added in v1.0.12

func (o KV) GetBool(key string) bool

GetBool returns the value for key as a bool.

func (KV) GetBoolForDefault added in v1.0.12

func (o KV) GetBoolForDefault(key string, defaultValue bool) bool

GetBoolForDefault returns the value for key as a bool, or defaultValue if the key is not present.

func (KV) GetFloat added in v1.0.12

func (o KV) GetFloat(key string) float64

GetFloat returns the value for key as a float64.

func (KV) GetInt added in v1.0.4

func (o KV) GetInt(key string) int

GetInt returns the value for key as an int.

func (KV) GetInt64 added in v1.0.12

func (o KV) GetInt64(key string) int64

GetInt64 returns the value for key as an int64.

func (KV) GetIntForDefault added in v1.0.4

func (o KV) GetIntForDefault(key string, defaultValue int) int

GetIntForDefault returns the value for key as an int, or defaultValue if the key is not present.

func (KV) GetMap added in v1.0.12

func (o KV) GetMap(key string) KV

GetMap returns the value for key as a KV (map), or nil.

func (KV) GetString added in v1.0.4

func (o KV) GetString(key string) string

GetString returns the value for key as a string.

func (KV) GetStringForDefault added in v1.0.12

func (o KV) GetStringForDefault(key string, defaultValue string) string

GetStringForDefault returns the value for key as a string, or defaultValue if the key is not present.

func (KV) GetStrings added in v1.0.12

func (o KV) GetStrings(key string) []string

GetStrings returns the value for key as a []string, or nil.

func (KV) GetUint added in v1.0.12

func (o KV) GetUint(key string) uint

GetUint returns the value for key as a uint.

func (KV) GetUint64 added in v1.0.12

func (o KV) GetUint64(key string) uint64

GetUint64 returns the value for key as a uint64.

func (KV) Has added in v1.0.12

func (o KV) Has(key string) bool

Has returns true if the key exists in the KV.

type MemFileSystem added in v0.1.2

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

MemFileSystem is a memory-cached file system that reads from disk locations and caches files in memory for faster subsequent access.

func DefaultMemFileSystem added in v0.1.2

func DefaultMemFileSystem(locations []string) *MemFileSystem

DefaultMemFileSystem creates a MemFileSystem with a 10-minute cache duration.

func NewMemFileSystem added in v0.1.2

func NewMemFileSystem(cacheTime time.Duration, locations []string) *MemFileSystem

NewMemFileSystem creates a MemFileSystem with the given cache duration and server config.

func (*MemFileSystem) Exists added in v0.1.2

func (m *MemFileSystem) Exists(name string) (bool, error)

Exists reports whether a file exists in any configured location.

func (*MemFileSystem) ExistsFile added in v1.0.12

func (m *MemFileSystem) ExistsFile(name string) (bool, error)

ExistsFile reports whether a file (not a directory) exists in any configured location.

func (*MemFileSystem) Open added in v0.1.2

func (m *MemFileSystem) Open(name string) (http.File, error)

Open opens a file by name, searching configured locations.

func (*MemFileSystem) Stat added in v0.1.2

func (m *MemFileSystem) Stat(name string) (os.FileInfo, error)

Stat returns file info for the named file, searching configured locations.

type Message

type Message struct {
	Code int    `json:"code"`
	Data any    `json:"data"`
	Msg  string `json:"msg"`
	Type string `json:"type"`
}

Message is the standard response format for the framework.

func Data

func Data(data any) *Message

Data creates a success response with the given data.

func DataCode added in v0.1.1

func DataCode(code int, data any) *Message

DataCode creates a response with a custom status code and data.

func DataType added in v0.1.1

func DataType(t string, data any) *Message

DataType creates a success response with a custom type and data.

func Ok

func Ok(msg ...string) *Message

Ok creates a success response with an optional message.

func Redirect added in v0.1.1

func Redirect(url string) *Message

Redirect creates a redirect response with the given URL.

func (*Message) IsOK

func (msg *Message) IsOK() bool

IsOK reports whether the message code indicates success (200).

type MetaOption added in v0.1.3

type MetaOption interface {
	// contains filtered or unexported methods
}

MetaOption is an option that can be applied to a HandlerMeta.

func WithKey added in v0.1.3

func WithKey(keys ...string) MetaOption

WithKey creates a MetaOption that sets the given keys to true in the handler metadata.

func WithValue added in v0.1.3

func WithValue(key string, value any) MetaOption

WithValue creates a MetaOption that sets a key-value pair in the handler metadata.

type Page

type Page = util.Page

Page represents pagination parameters for list queries. Alias for util.Page to keep backward compatibility.

type PageAble

type PageAble[T any] = util.PageAble[T]

PageAble is a paginated response wrapper containing total count and item list. Alias for util.PageAble to keep backward compatibility.

func ToPage

func ToPage[T any](total int64, list []T) *PageAble[T]

ToPage creates a new PageAble from the given total count and item list. Delegates to util.ToPage for backward compatibility.

type Request

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

Request wraps the HTTP request with helper methods for accessing parameters, query strings, JSON body, headers, and client info.

func NewRequestForTest added in v0.7.2

func NewRequestForTest(ctx *gin.Context, resp Response, meta *HandlerMeta) *Request

NewRequestForTest creates a Request for testing purposes.

func (*Request) BindJSON

func (r *Request) BindJSON(value any) error

BindJSON binds the request JSON body into the provided struct.

func (*Request) ClientIP added in v0.5.1

func (r *Request) ClientIP() string

ClientIP returns the client IP as resolved by Gin.

func (*Request) ContentType added in v0.1.3

func (r *Request) ContentType() string

ContentType returns the request Content-Type header.

func (*Request) ContextPath added in v0.7.1

func (r *Request) ContextPath() string

ContextPath returns the configured context path prefix (e.g. "/api/v1").

func (*Request) Cookie

func (r *Request) Cookie() *Cookie

Cookie returns the cookie helper for this request.

func (*Request) Ctx added in v0.9.4

func (r *Request) Ctx() context.Context

Ctx returns the context.Context for the current HTTP request. The context is automatically cancelled when the request completes. Use this to propagate request-scoped cancellation, timeouts, and tracing to database operations.

func (*Request) Domain

func (r *Request) Domain() string

Domain returns the request host without the port.

func (*Request) FormParamsPage

func (r *Request) FormParamsPage() (*Page, error)

FormParamsPage extracts pagination parameters from form/query parameters.

func (*Request) FullPath added in v0.1.2

func (r *Request) FullPath() string

FullPath returns the full matched route path.

func (*Request) GetFormParam

func (r *Request) GetFormParam(key string) string

GetFormParam returns a form parameter value by key.

func (*Request) GetHeader added in v0.1.3

func (r *Request) GetHeader(s string) string

GetHeader returns the value of the request header for the given key.

func (*Request) GetIntFormParam

func (r *Request) GetIntFormParam(key string) int

GetIntFormParam returns a form parameter value as an int.

func (*Request) GetIntFormParamOrDefault

func (r *Request) GetIntFormParamOrDefault(key string, defaultValue int) int

GetIntFormParamOrDefault returns a form parameter value as an int, or defaultValue if the param is not set.

func (*Request) GetJsonIntValue

func (r *Request) GetJsonIntValue(key string) (int, error)

GetJsonIntValue returns an int value from the JSON body.

func (*Request) GetJsonIntValueOrDefault

func (r *Request) GetJsonIntValueOrDefault(key string, defaultValue int) int

GetJsonIntValueOrDefault returns an int value from the JSON body, or defaultValue if the key is not present.

func (*Request) GetJsonStringValue

func (r *Request) GetJsonStringValue(key string) (string, error)

GetJsonStringValue returns a string value from the JSON body.

func (*Request) GetJsonStringValueOrDefault

func (r *Request) GetJsonStringValueOrDefault(key string, defaultValue string) string

GetJsonStringValueOrDefault returns a string value from the JSON body, or defaultValue if empty.

func (*Request) GinContext added in v0.1.1

func (r *Request) GinContext() *gin.Context

GinContext returns the underlying *gin.Context. Not recommended for use — prefer the Request helper methods. Only reach for this when you need to reuse libraries or middleware from the gin ecosystem.

func (*Request) HandlerMeta added in v0.1.3

func (r *Request) HandlerMeta() *HandlerMeta

HandlerMeta returns the metadata attached to the matched route handler.

func (*Request) HasMeta added in v1.0.5

func (r *Request) HasMeta(mo ...MetaOption) bool

func (*Request) IsGet

func (r *Request) IsGet() bool

IsGet reports whether the request method is GET.

func (*Request) IsMultipartForm added in v0.1.3

func (r *Request) IsMultipartForm() bool

IsMultipartForm reports whether the request is a multipart form.

func (*Request) IsPost

func (r *Request) IsPost() bool

IsPost reports whether the request method is POST.

func (*Request) Json

func (r *Request) Json() (*JSONObject, error)

Json parses the request body as JSON and returns it as a JSONObject. The result is cached on subsequent calls. The body size is limited by ServerConfig.MaxBodySize (default 10 MB).

func (*Request) JsonPage

func (r *Request) JsonPage() (*Page, error)

JsonPage extracts pagination parameters (pageNo, pageSize, lastId) from the JSON body.

func (*Request) MultipartForm added in v0.1.3

func (r *Request) MultipartForm() (*multipart.Form, error)

MultipartForm returns the parsed multipart form.

func (*Request) Page

func (r *Request) Page() (*Page, error)

Page extracts pagination parameters from the request. For GET requests, it reads from query/form parameters. For POST requests, it reads from the JSON body.

func (*Request) Param added in v0.1.1

func (r *Request) Param(key string) string

Param returns the path parameter value for the given key.

func (*Request) ParamInt added in v0.1.2

func (r *Request) ParamInt(key string) int

ParamInt returns the path parameter value as an int.

func (*Request) ParamIntForDefault added in v0.5.1

func (r *Request) ParamIntForDefault(key string, defaultValue int) int

ParamIntForDefault returns the path parameter value as an int, or defaultValue if the param is empty.

func (*Request) ParamUint added in v0.1.2

func (r *Request) ParamUint(key string) uint

ParamUint returns the path parameter value as a uint.

func (*Request) Query added in v0.1.2

func (r *Request) Query(key string) string

Query returns the query parameter value for the given key.

func (*Request) RemoteAddr

func (r *Request) RemoteAddr() string

RemoteAddr returns the raw remote address string (host:port).

func (*Request) RemoteIp added in v0.1.3

func (r *Request) RemoteIp() string

RemoteIp returns the real client IP, supporting X-Forwarded-For headers.

func (*Request) Request added in v0.1.3

func (r *Request) Request() *http.Request

Request returns the underlying *http.Request.

func (*Request) Response added in v0.1.3

func (r *Request) Response() Response

Response returns the Response writer for this request.

func (*Request) URL added in v0.1.3

func (r *Request) URL() *url.URL

URL returns the parsed request URL.

type Response

type Response interface {
	gin.ResponseWriter
	// SetAttachmentFileName sets the Content-Disposition header for file downloads.
	SetAttachmentFileName(fileName string)
	// JSON writes a JSON response with the given status code and value.
	JSON(code int, value any)
	// Abort stops further handler execution.
	Abort()
	// Redirect sends an HTTP redirect to the client.
	Redirect(code int, location string)
	// FileAttachment sends a file as an attachment download.
	FileAttachment(path string, name string)
	// WriteStatus writes only the HTTP status code.
	WriteStatus(code int)
	// AbortWithStatusJSON writes a JSON response with the given status and aborts.
	AbortWithStatusJSON(i int, value any)
	// AbortWithError writes an error response and returns the error.
	AbortWithError(err error) error
	// Message writes a Message as JSON response.
	Message(t *Message)
	// AbortWithMessage writes a Message and aborts the handler chain.
	AbortWithMessage(t *Message)
}

Response is the interface for writing HTTP responses with JSON, files, and redirects.

type ResponseWriteCloser

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

ResponseWriteCloser wraps a Response to implement io.WriteCloser. Close flushes the response.

func CreateResponseWriteCloser

func CreateResponseWriteCloser(response Response) *ResponseWriteCloser

CreateResponseWriteCloser creates a ResponseWriteCloser from a Response.

func (*ResponseWriteCloser) Close

func (w *ResponseWriteCloser) Close() error

Close flushes the response writer.

func (*ResponseWriteCloser) Write

func (w *ResponseWriteCloser) Write(p []byte) (n int, err error)

Write writes bytes to the underlying response.

type ReverseProxyResponse added in v1.0.4

type ReverseProxyResponse struct {
	Target string
}

ReverseProxyResponse is a handler return value that signals the converter to reverse-proxy the request to the given target URL.

type Route added in v1.0.4

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

Route represents an HTTP route with its path, methods, and handlers.

func (*Route) LastFuncName added in v1.0.4

func (r *Route) LastFuncName() string

LastFuncName returns the fully-qualified function name of the last handler in the route. Used for debug logging; returns empty string if the route has no handlers.

func (*Route) WithMeta added in v1.0.4

func (r *Route) WithMeta(mo ...MetaOption) *Route

WithMeta adds the given MetaOption values to the route's metadata. If handlerMeta is nil, a new one is created automatically.

type SSEHandler added in v0.7.1

type SSEHandler func(stream *SSEStream) error

SSEHandler is the function signature for SSE stream handlers.

type SSEResponse added in v1.0.4

type SSEResponse struct {
	Handler SSEHandler
}

SSEResponse is a handler return value that signals the converter to set up an SSE stream and invoke the handler.

type SSEStream added in v0.7.1

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

SSEStream represents a Server-Sent Events stream backed by a web Request.

func NewSSEStream added in v0.7.1

func NewSSEStream(r *Request) *SSEStream

NewSSEStream creates a new SSE stream from a web Request.

func (*SSEStream) Close added in v0.7.1

func (s *SSEStream) Close()

Close closes the SSE stream and waits for all background goroutines to exit.

func (*SSEStream) Context added in v1.0.4

func (s *SSEStream) Context() context.Context

Context returns the stream's context, cancelled when the stream closes.

func (*SSEStream) Done added in v0.7.1

func (s *SSEStream) Done() <-chan struct{}

Done returns a channel that is closed when the stream is closed.

func (*SSEStream) Heartbeat added in v0.7.1

func (s *SSEStream) Heartbeat() error

Heartbeat sends a comment line to keep the connection alive.

func (*SSEStream) Request added in v1.0.4

func (s *SSEStream) Request() *Request

Request returns the underlying web Request.

func (*SSEStream) Send added in v0.7.1

func (s *SSEStream) Send(event string, data string) error

Send sends an SSE event with the given event name and data.

func (*SSEStream) SendMessage added in v0.7.1

func (s *SSEStream) SendMessage(data string) error

SendMessage sends a default message event without a named event type.

func (*SSEStream) SendRetry added in v0.7.1

func (s *SSEStream) SendRetry(retryMs int) error

SendRetry sends a reconnection interval hint (in milliseconds) to the client.

func (*SSEStream) SendWithID added in v0.7.1

func (s *SSEStream) SendWithID(id string, event string, data string) error

SendWithID sends an SSE event with an ID, event name, and data.

func (*SSEStream) SetHeader added in v1.0.4

func (s *SSEStream) SetHeader(key string, value string)

SetHeader sets a custom header on the SSE response.

func (*SSEStream) SetHeaders added in v0.7.1

func (s *SSEStream) SetHeaders()

SetHeaders writes the standard SSE headers on the response.

func (*SSEStream) StartHeartbeat added in v0.7.1

func (s *SSEStream) StartHeartbeat(interval time.Duration)

StartHeartbeat starts a periodic heartbeat goroutine that sends SSE comment lines at the given interval. The goroutine exits automatically when the stream is closed or the request disconnects. Close() blocks until the heartbeat goroutine has fully exited.

func (*SSEStream) StartHeartbeatWithContext added in v1.0.4

func (s *SSEStream) StartHeartbeatWithContext(ctx context.Context, interval time.Duration)

StartHeartbeatWithContext starts a periodic heartbeat goroutine with an external context. The goroutine exits when ctx is cancelled, the stream is closed, or the request disconnects. Close() blocks until the goroutine exits.

type SSLCertificate added in v1.0.4

type SSLCertificate struct {
	CertFile string // Path to the certificate file (PEM format)
	KeyFile  string // Path to the private key file (PEM format)
}

SSLCertificate holds paths to a TLS certificate and private key file.

type SSLConfig added in v0.1.1

type SSLConfig struct {
	Enabled bool             // Whether HTTPS is enabled
	Hosts   []string         // Domain names for Let's Encrypt auto-certification
	Certs   []SSLCertificate // Local certificate entries for pre-obtained certificates
}

SSLConfig holds TLS/HTTPS configuration with optional auto-certification hosts.

type Server added in v1.0.4

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

Server is an HTTP server with routing, filters, and static file support.

func DefaultServer added in v1.0.4

func DefaultServer() *Server

func (*Server) AddFilter added in v1.0.4

func (server *Server) AddFilter(filter Filter)

AddFilter appends a filter (middleware) to the server's filter chain.

func (*Server) AddFilters added in v1.0.12

func (server *Server) AddFilters(filters ...Filter)

func (*Server) AddHandles added in v1.0.4

func (server *Server) AddHandles(handles *Handles)

AddHandles transfers all routes from the given Handles into this Server.

func (*Server) AddReverseProxy added in v1.0.4

func (server *Server) AddReverseProxy(relativePath string, target string) *Route

AddReverseProxy registers a reverse proxy route on this server for all HTTP methods. The relativePath should be a prefix (e.g. "/api"); a wildcard is appended automatically so that "/api/hello" matches in addition to "/api".

func (*Server) AddSSE added in v1.0.4

func (server *Server) AddSSE(relativePath string, handler SSEHandler) *Route

AddSSE registers a Server-Sent Events endpoint on this server.

func (*Server) AddStaticFs added in v1.0.4

func (server *Server) AddStaticFs(relativePath string, fs http.FileSystem) *Route

AddStaticFs registers a static file server at the given path on this server.

func (*Server) AddWebSocket added in v1.0.4

func (server *Server) AddWebSocket(relativePath string, handler WebSocketHandler) *Route

AddWebSocket registers a WebSocket endpoint on this server.

func (*Server) Any added in v1.0.4

func (server *Server) Any(relativePath string, handlers ...HandlerFunc) *Route

Any registers a route handler for all HTTP methods on this server.

func (*Server) Delete added in v1.0.4

func (server *Server) Delete(relativePath string, handlers ...HandlerFunc) *Route

Delete registers a DELETE route handler on this server.

func (*Server) Get added in v1.0.4

func (server *Server) Get(relativePath string, handlers ...HandlerFunc) *Route

Get registers a GET route handler on this server.

func (*Server) GetHandler added in v1.0.4

func (server *Server) GetHandler() http.Handler

func (*Server) Handle added in v1.0.4

func (server *Server) Handle(httpMethod string, relativePath string, handlers ...HandlerFunc) *Route

Handle registers a handler for a single HTTP method on this server.

func (*Server) Handlers added in v1.0.4

func (server *Server) Handlers(httpMethods []string, relativePath string, handlers ...HandlerFunc) *Route

Handlers registers a handler for multiple HTTP methods on this server.

func (*Server) Listen added in v1.0.12

func (server *Server) Listen(ctx context.Context, certs *certStore) error

func (*Server) ListenTLS added in v1.0.12

func (server *Server) ListenTLS(ctx context.Context, certs *certStore) error

func (*Server) Patch added in v1.0.4

func (server *Server) Patch(relativePath string, handlers ...HandlerFunc) *Route

Patch registers a PATCH route handler on this server.

func (*Server) Port added in v1.0.4

func (server *Server) Port() int

Port returns the configured listen port for this server.

func (*Server) Post added in v1.0.4

func (server *Server) Post(relativePath string, handlers ...HandlerFunc) *Route

Post registers a POST route handler on this server.

func (*Server) Put added in v1.0.4

func (server *Server) Put(relativePath string, handlers ...HandlerFunc) *Route

Put registers a PUT route handler on this server.

func (*Server) ServerConfig added in v1.0.12

func (server *Server) ServerConfig() *ServerConfig

func (*Server) SetConverter added in v1.0.4

func (server *Server) SetConverter(converter Converter)

SetConverter sets a custom converter that transforms handler results to HTTP responses.

type ServerConfig added in v0.1.1

type ServerConfig struct {
	Port              int        // Listen port (default: 19009)
	ContextPath       string     // Route prefix applied to all routes (e.g., "/api")
	Locations         []string   // Static file directories to serve
	Page404           string     // Fallback page for 404 responses (useful for SPA)
	MaxBodySize       int64      // Maximum request body size in bytes (0 = default 10 MB, -1 = unlimited)
	ReadHeaderTimeout int        // Timeout in seconds for reading request headers (0 = default 30s)
	ReadTimeout       int        // Timeout in seconds for reading the entire request (0 = default 10min)
	MaxHeaderBytes    int        // Maximum size of request headers in bytes (0 = default 8192)
	SSL               *SSLConfig // HTTPS/TLS configuration
}

ServerConfig holds the HTTP server configuration including port, context path, and TLS.

func DefaultServerConfig added in v0.1.1

func DefaultServerConfig() *ServerConfig

DefaultServerConfig returns a ServerConfig with default values.

func (*ServerConfig) GetMaxHeaderBytes added in v1.0.8

func (sc *ServerConfig) GetMaxHeaderBytes() int

GetMaxHeaderBytes returns the configured MaxHeaderBytes or the default (8192).

func (*ServerConfig) GetReadHeaderTimeout added in v1.0.8

func (sc *ServerConfig) GetReadHeaderTimeout() time.Duration

GetReadHeaderTimeout returns the configured ReadHeaderTimeout (seconds) or the default (30s).

func (*ServerConfig) GetReadTimeout added in v1.0.8

func (sc *ServerConfig) GetReadTimeout() time.Duration

GetReadTimeout returns the configured ReadTimeout (seconds) or the default (10min).

func (*ServerConfig) SSLEnabled added in v0.1.1

func (sc *ServerConfig) SSLEnabled() bool

SSLEnabled reports whether HTTPS is enabled in this configuration.

type ServerRunner added in v1.0.4

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

ServerRunner manages HTTP and TLS listeners with auto-certification support.

func (*ServerRunner) Start added in v1.0.4

func (sr *ServerRunner) Start() error

type Servers added in v1.0.4

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

Servers manages multiple HTTP servers that can be started together.

func NewServerWithContext added in v1.0.4

func NewServerWithContext(ctx context.Context) *Servers

NewServerWithContext creates a new Servers instance with the given context.

func NewServers added in v1.0.4

func NewServers() *Servers

NewServers creates a new Servers instance with release mode and background context.

func (*Servers) CreateServer added in v1.0.4

func (servers *Servers) CreateServer(serverConfig *ServerConfig) (*Server, error)

CreateServer creates a new Server with the given config using the Servers' context.

func (*Servers) CreateServerWithContext added in v1.0.4

func (servers *Servers) CreateServerWithContext(serverConfig *ServerConfig, ctx context.Context) (*Server, error)

CreateServerWithContext creates a new Server with the given config and context, checking for port conflicts.

func (*Servers) GetHandler added in v1.0.11

func (servers *Servers) GetHandler() http.Handler

GetHandler returns an http.Handler that dispatches requests to the correct Server based on the port in the request's Host header. Each Server's routes, filters, and ContextPath are fully independent.

func (*Servers) GetServers added in v1.0.4

func (servers *Servers) GetServers() []*Server

func (*Servers) Start added in v1.0.4

func (servers *Servers) Start() error

Start starts all managed servers with TLS and auto-cert support.

type WSResponse added in v1.0.4

type WSResponse struct {
	Handler WebSocketHandler
}

WSResponse is a handler return value that signals the converter to accept the WebSocket upgrade and invoke the handler.

type WebSocket added in v1.0.13

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

func (*WebSocket) Close added in v1.0.13

func (webSocket *WebSocket) Close()

func (*WebSocket) OpenStream added in v1.0.13

func (webSocket *WebSocket) OpenStream(opts ...AcceptOptions) (*WebSocketStream, error)

OpenStream accepts the WebSocket connection with the given options and returns the ready-to-use stream. Must be called before any Read/Write.

func (*WebSocket) Request added in v1.0.13

func (webSocket *WebSocket) Request() *Request

Request returns the original HTTP request that initiated the WebSocket upgrade.

type WebSocketHandler added in v0.7.1

type WebSocketHandler func(webSocket *WebSocket) error

WebSocketHandler is the function signature for WebSocket stream handlers.

type WebSocketStream added in v1.0.4

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

WebSocketStream wraps a coder/websocket connection with Request and context.

func (*WebSocketStream) Close added in v1.0.4

func (ws *WebSocketStream) Close()

Close closes the WebSocket connection and cancels the stream context.

func (*WebSocketStream) Conn added in v1.0.4

func (ws *WebSocketStream) Conn() *websocket.Conn

Conn returns the underlying WebSocket connection.

func (*WebSocketStream) Context added in v1.0.4

func (ws *WebSocketStream) Context() context.Context

Context returns the stream context, cancelled on Close or request disconnect.

func (*WebSocketStream) Done added in v1.0.4

func (ws *WebSocketStream) Done() <-chan struct{}

Done returns a channel that is closed when the stream is closed or the request disconnects.

func (*WebSocketStream) Ping added in v1.0.4

func (ws *WebSocketStream) Ping(ctx context.Context) error

Ping sends a ping frame to the client.

func (*WebSocketStream) Read added in v1.0.4

Read reads any message type from the WebSocket connection.

func (*WebSocketStream) ReadText added in v1.0.4

func (ws *WebSocketStream) ReadText(ctx context.Context) ([]byte, error)

ReadText reads a text message, returning an error if the message is not text.

func (*WebSocketStream) Request added in v1.0.4

func (ws *WebSocketStream) Request() *Request

Request returns the underlying web2 Request.

func (*WebSocketStream) Write added in v1.0.4

func (ws *WebSocketStream) Write(ctx context.Context, typ websocket.MessageType, data []byte) error

Write writes a message to the WebSocket connection.

func (*WebSocketStream) WriteBinary added in v1.0.4

func (ws *WebSocketStream) WriteBinary(ctx context.Context, data []byte) error

WriteBinary writes a binary message.

func (*WebSocketStream) WriteString added in v1.0.4

func (ws *WebSocketStream) WriteString(ctx context.Context, s string) error

WriteString writes a text message from a string.

func (*WebSocketStream) WriteText added in v1.0.4

func (ws *WebSocketStream) WriteText(ctx context.Context, data []byte) error

WriteText writes a text message.

Jump to

Keyboard shortcuts

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