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
- Variables
- func ClassifyError(value any, err error) (int, string)
- func SaveUploadedFile(file *multipart.FileHeader, dst string) error
- type AcceptOptions
- func WithCompressionMode(mode int) AcceptOptions
- func WithCompressionThreshold(threshold int) AcceptOptions
- func WithInsecureSkipVerify(skip bool) AcceptOptions
- func WithOnPingReceived(fn func(ctx context.Context, payload []byte) bool) AcceptOptions
- func WithOnPongReceived(fn func(ctx context.Context, payload []byte)) AcceptOptions
- func WithOriginPatterns(OriginPatterns []string) AcceptOptions
- func WithSubprotocols(subprotocols ...string) AcceptOptions
- type Converter
- type Cookie
- func (c *Cookie) Delete(key string)
- func (c *Cookie) Expire(key string)
- func (c *Cookie) Forever(key string, value string, opts ...CookieOption)
- func (c *Cookie) ForeverDomain(domain string, key string, value string, opts ...CookieOption)
- func (c *Cookie) Get(key string) string
- func (c *Cookie) Set(key string, value string, opts ...CookieOption)
- func (c *Cookie) SetDomain(domain string, key string, value string, opts ...CookieOption)
- func (c *Cookie) SetWithExpire(key string, value string, expire int, opts ...CookieOption)
- func (c *Cookie) Update(key string, value string)
- type CookieOption
- type DefaultConverter
- func (c *DefaultConverter) Error(request *Request, value any, err error)
- func (c *DefaultConverter) FileResponse(request *Request, value *FileResponse)
- func (c *DefaultConverter) FileSystemResponse(request *Request, value *FileSystemResponse)
- func (c *DefaultConverter) Message(request *Request, value *Message)
- func (c *DefaultConverter) RawFile(request *Request, value *os.File)
- func (c *DefaultConverter) Request(filterChain FilterChain, request *Request)
- func (c *DefaultConverter) ReverseProxyResponse(request *Request, value *ReverseProxyResponse)
- func (c *DefaultConverter) SSEResponse(request *Request, value *SSEResponse)
- func (c *DefaultConverter) String(request *Request, value string)
- func (c *DefaultConverter) WSResponse(request *Request, value *WSResponse)
- type ErrorCode
- func NewBadRequest() *ErrorCode
- func NewDuplicateEntry() *ErrorCode
- func NewErrorCode(code int, msg string) *ErrorCode
- func NewErrorCodeWithError(code int, err error) *ErrorCode
- func NewForbidden() *ErrorCode
- func NewInternalError() *ErrorCode
- func NewMethodNotAllowed() *ErrorCode
- func NewNotFound() *ErrorCode
- func NewServiceUnavailable() *ErrorCode
- func NewTokenExpired() *ErrorCode
- func NewTokenInvalid() *ErrorCode
- func NewTooManyRequests() *ErrorCode
- func NewUnauthorized() *ErrorCode
- func NewValidationError() *ErrorCode
- type FileResponse
- type FileSystemResponse
- type Filter
- type FilterChain
- type HandlerChain
- type HandlerFunc
- type HandlerMeta
- type Handles
- func (h *Handles) AddReverseProxy(relativePath string, target string) *Route
- func (h *Handles) AddSSE(relativePath string, handler SSEHandler) *Route
- func (h *Handles) AddStaticFs(relativePath string, fs http.FileSystem) *Route
- func (h *Handles) AddWebSocket(relativePath string, handler WebSocketHandler) *Route
- func (h *Handles) Any(relativePath string, handlers ...HandlerFunc) *Route
- func (h *Handles) Delete(relativePath string, handlers ...HandlerFunc) *Route
- func (h *Handles) Empty() bool
- func (h *Handles) Get(relativePath string, handlers ...HandlerFunc) *Route
- func (h *Handles) Handle(httpMethod string, relativePath string, handlers ...HandlerFunc) *Route
- func (h *Handles) Handlers(httpMethods []string, relativePath string, handlers ...HandlerFunc) *Route
- func (h *Handles) Patch(relativePath string, handlers ...HandlerFunc) *Route
- func (h *Handles) Post(relativePath string, handlers ...HandlerFunc) *Route
- func (h *Handles) Put(relativePath string, handlers ...HandlerFunc) *Route
- type JSONObject
- type KV
- func (o KV) Add(key string, value any)
- func (o KV) GetArray(key string) []any
- func (o KV) GetBool(key string) bool
- func (o KV) GetBoolForDefault(key string, defaultValue bool) bool
- func (o KV) GetFloat(key string) float64
- func (o KV) GetInt(key string) int
- func (o KV) GetInt64(key string) int64
- func (o KV) GetIntForDefault(key string, defaultValue int) int
- func (o KV) GetMap(key string) KV
- func (o KV) GetString(key string) string
- func (o KV) GetStringForDefault(key string, defaultValue string) string
- func (o KV) GetStrings(key string) []string
- func (o KV) GetUint(key string) uint
- func (o KV) GetUint64(key string) uint64
- func (o KV) Has(key string) bool
- type MemFileSystem
- type Message
- type MetaOption
- type Page
- type PageAble
- type Request
- func (r *Request) BindJSON(value any) error
- func (r *Request) ClientIP() string
- func (r *Request) ContentType() string
- func (r *Request) ContextPath() string
- func (r *Request) Cookie() *Cookie
- func (r *Request) Ctx() context.Context
- func (r *Request) Domain() string
- func (r *Request) FormParamsPage() (*Page, error)
- func (r *Request) FullPath() string
- func (r *Request) GetFormParam(key string) string
- func (r *Request) GetHeader(s string) string
- func (r *Request) GetIntFormParam(key string) int
- func (r *Request) GetIntFormParamOrDefault(key string, defaultValue int) int
- func (r *Request) GetJsonIntValue(key string) (int, error)
- func (r *Request) GetJsonIntValueOrDefault(key string, defaultValue int) int
- func (r *Request) GetJsonStringValue(key string) (string, error)
- func (r *Request) GetJsonStringValueOrDefault(key string, defaultValue string) string
- func (r *Request) GinContext() *gin.Context
- func (r *Request) HandlerMeta() *HandlerMeta
- func (r *Request) HasMeta(mo ...MetaOption) bool
- func (r *Request) IsGet() bool
- func (r *Request) IsMultipartForm() bool
- func (r *Request) IsPost() bool
- func (r *Request) Json() (*JSONObject, error)
- func (r *Request) JsonPage() (*Page, error)
- func (r *Request) MultipartForm() (*multipart.Form, error)
- func (r *Request) Page() (*Page, error)
- func (r *Request) Param(key string) string
- func (r *Request) ParamInt(key string) int
- func (r *Request) ParamIntForDefault(key string, defaultValue int) int
- func (r *Request) ParamUint(key string) uint
- func (r *Request) Query(key string) string
- func (r *Request) RemoteAddr() string
- func (r *Request) RemoteIp() string
- func (r *Request) Request() *http.Request
- func (r *Request) Response() Response
- func (r *Request) URL() *url.URL
- type Response
- type ResponseWriteCloser
- type ReverseProxyResponse
- type Route
- type SSEHandler
- type SSEResponse
- type SSEStream
- func (s *SSEStream) Close()
- func (s *SSEStream) Context() context.Context
- func (s *SSEStream) Done() <-chan struct{}
- func (s *SSEStream) Heartbeat() error
- func (s *SSEStream) Request() *Request
- func (s *SSEStream) Send(event string, data string) error
- func (s *SSEStream) SendMessage(data string) error
- func (s *SSEStream) SendRetry(retryMs int) error
- func (s *SSEStream) SendWithID(id string, event string, data string) error
- func (s *SSEStream) SetHeader(key string, value string)
- func (s *SSEStream) SetHeaders()
- func (s *SSEStream) StartHeartbeat(interval time.Duration)
- func (s *SSEStream) StartHeartbeatWithContext(ctx context.Context, interval time.Duration)
- type SSLCertificate
- type SSLConfig
- type Server
- func (server *Server) AddFilter(filter Filter)
- func (server *Server) AddFilters(filters ...Filter)
- func (server *Server) AddHandles(handles *Handles)
- func (server *Server) AddReverseProxy(relativePath string, target string) *Route
- func (server *Server) AddSSE(relativePath string, handler SSEHandler) *Route
- func (server *Server) AddStaticFs(relativePath string, fs http.FileSystem) *Route
- func (server *Server) AddWebSocket(relativePath string, handler WebSocketHandler) *Route
- func (server *Server) Any(relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) Delete(relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) Get(relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) GetHandler() http.Handler
- func (server *Server) Handle(httpMethod string, relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) Handlers(httpMethods []string, relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) Listen(ctx context.Context, certs *certStore) error
- func (server *Server) ListenTLS(ctx context.Context, certs *certStore) error
- func (server *Server) Patch(relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) Port() int
- func (server *Server) Post(relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) Put(relativePath string, handlers ...HandlerFunc) *Route
- func (server *Server) ServerConfig() *ServerConfig
- func (server *Server) SetConverter(converter Converter)
- type ServerConfig
- type ServerRunner
- type Servers
- func (servers *Servers) CreateServer(serverConfig *ServerConfig) (*Server, error)
- func (servers *Servers) CreateServerWithContext(serverConfig *ServerConfig, ctx context.Context) (*Server, error)
- func (servers *Servers) GetHandler() http.Handler
- func (servers *Servers) GetServers() []*Server
- func (servers *Servers) Start() error
- type WSResponse
- type WebSocket
- type WebSocketHandler
- type WebSocketStream
- func (ws *WebSocketStream) Close()
- func (ws *WebSocketStream) Conn() *websocket.Conn
- func (ws *WebSocketStream) Context() context.Context
- func (ws *WebSocketStream) Done() <-chan struct{}
- func (ws *WebSocketStream) Ping(ctx context.Context) error
- func (ws *WebSocketStream) Read(ctx context.Context) (websocket.MessageType, []byte, error)
- func (ws *WebSocketStream) ReadText(ctx context.Context) ([]byte, error)
- func (ws *WebSocketStream) Request() *Request
- func (ws *WebSocketStream) Write(ctx context.Context, typ websocket.MessageType, data []byte) error
- func (ws *WebSocketStream) WriteBinary(ctx context.Context, data []byte) error
- func (ws *WebSocketStream) WriteString(ctx context.Context, s string) error
- func (ws *WebSocketStream) WriteText(ctx context.Context, data []byte) error
Constants ¶
const ( CodeOK = 200 CodeBadRequest = 400 CodeForbidden = 403 CodeNotFound = 404 CodeMethodNotAllowed = 405 CodeTooManyRequests = 429 CodeInternalError = 500 // Business error codes (1000+) CodeValidationFailed = 1001 CodeDuplicateEntry = 1002 CodeTokenExpired = 1003 CodeTokenInvalid = 1004 )
Error code constants
const DefaultMaxBodySize int64 = 10 << 20
DefaultMaxBodySize is the default maximum request body size (10 MB).
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.
const MaxHeaderBytes = 8192
MaxHeaderBytes is the maximum size of request headers in bytes.
const MaxReadHeaderTimeout = time.Second * 30
MaxReadHeaderTimeout is the maximum duration for reading request headers.
const MaxReadTimeout = time.Minute * 10
MaxReadTimeout is the maximum duration for reading the entire request.
const ServerConfigKey = "web.server"
ServerConfigKey is the configuration key for server settings.
Variables ¶
var ( ErrBadRequest = NewErrorCode(CodeBadRequest, "bad request") 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") 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
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 ¶
type Cookie struct {
// contains filtered or unexported fields
}
Cookie provides helper methods for reading, writing, and deleting HTTP cookies.
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) 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.
type CookieOption ¶ added in v1.0.4
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
NewErrorCode creates a new ErrorCode with the given code and message.
func NewErrorCodeWithError ¶ added in v1.0.7
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) Unwrap ¶ added in v1.0.7
Unwrap returns the wrapped error, supporting errors.Is/As chains.
func (*ErrorCode) WithDetail ¶ added in v0.7.3
WithDetail attaches additional detail information to 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 ¶
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
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) 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.
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
KV is a string-keyed map with type-safe accessor methods.
func (KV) GetBoolForDefault ¶ added in v1.0.12
GetBoolForDefault returns the value for key as a bool, or defaultValue if the key is not present.
func (KV) GetIntForDefault ¶ added in v1.0.4
GetIntForDefault returns the value for key as an int, or defaultValue if the key is not present.
func (KV) GetStringForDefault ¶ added in v1.0.12
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
GetStrings returns the value for key as a []string, or nil.
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.
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.
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 ¶
Page represents pagination parameters for list queries. Alias for util.Page to keep backward compatibility.
type PageAble ¶
PageAble is a paginated response wrapper containing total count and item list. Alias for util.PageAble to keep 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) ContentType ¶ added in v0.1.3
ContentType returns the request Content-Type header.
func (*Request) ContextPath ¶ added in v0.7.1
ContextPath returns the configured context path prefix (e.g. "/api/v1").
func (*Request) Ctx ¶ added in v0.9.4
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) FormParamsPage ¶
FormParamsPage extracts pagination parameters from form/query parameters.
func (*Request) GetFormParam ¶
GetFormParam returns a form parameter value by key.
func (*Request) GetHeader ¶ added in v0.1.3
GetHeader returns the value of the request header for the given key.
func (*Request) GetIntFormParam ¶
GetIntFormParam returns a form parameter value as an int.
func (*Request) GetIntFormParamOrDefault ¶
GetIntFormParamOrDefault returns a form parameter value as an int, or defaultValue if the param is not set.
func (*Request) GetJsonIntValue ¶
GetJsonIntValue returns an int value from the JSON body.
func (*Request) GetJsonIntValueOrDefault ¶
GetJsonIntValueOrDefault returns an int value from the JSON body, or defaultValue if the key is not present.
func (*Request) GetJsonStringValue ¶
GetJsonStringValue returns a string value from the JSON body.
func (*Request) GetJsonStringValueOrDefault ¶
GetJsonStringValueOrDefault returns a string value from the JSON body, or defaultValue if empty.
func (*Request) GinContext ¶ added in v0.1.1
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) IsMultipartForm ¶ added in v0.1.3
IsMultipartForm reports whether the request is a multipart form.
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 ¶
JsonPage extracts pagination parameters (pageNo, pageSize, lastId) from the JSON body.
func (*Request) MultipartForm ¶ added in v0.1.3
MultipartForm returns the parsed multipart form.
func (*Request) Page ¶
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) ParamIntForDefault ¶ added in v0.5.1
ParamIntForDefault returns the path parameter value as an int, or defaultValue if the param is empty.
func (*Request) RemoteAddr ¶
RemoteAddr returns the raw remote address string (host:port).
func (*Request) RemoteIp ¶ added in v0.1.3
RemoteIp returns the real client IP, supporting X-Forwarded-For headers.
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.
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
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
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
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
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
Heartbeat sends a comment line to keep the connection alive.
func (*SSEStream) Send ¶ added in v0.7.1
Send sends an SSE event with the given event name and data.
func (*SSEStream) SendMessage ¶ added in v0.7.1
SendMessage sends a default message event without a named event type.
func (*SSEStream) SendRetry ¶ added in v0.7.1
SendRetry sends a reconnection interval hint (in milliseconds) to the client.
func (*SSEStream) SendWithID ¶ added in v0.7.1
SendWithID sends an SSE event with an ID, event name, and data.
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
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
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
AddFilter appends a filter (middleware) to the server's filter chain.
func (*Server) AddFilters ¶ added in v1.0.12
func (*Server) AddHandles ¶ added in v1.0.4
AddHandles transfers all routes from the given Handles into this Server.
func (*Server) AddReverseProxy ¶ added in v1.0.4
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) 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) 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) 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
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
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
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
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) 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.
type WebSocketHandler ¶ added in v0.7.1
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
func (ws *WebSocketStream) Read(ctx context.Context) (websocket.MessageType, []byte, error)
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.