Documentation
¶
Overview ¶
Package znet provides a lightweight and high-performance HTTP web framework.
It features a flexible router with middleware support, context-based request handling, and various utilities for building web applications and RESTful APIs.
Basic Usage:
package main
import (
"github.com/sohaha/zlsgo/znet"
)
func main() {
r := znet.New() // Create a new router instance
r.SetMode(znet.DebugMode) // Enable debug mode for development
// Define a simple route
r.GET("/", func(c znet.Context) {
c.String(200, "hello world")
})
// Define a route with path parameters
r.GET("/users/:id", func(c znet.Context) {
id := c.Param("id")
c.JSON(200, map[string]interface{}{
"id": id,
"message": "User details",
})
})
// Start the HTTP server
znet.Run()
}
The framework provides the following key features:
1. Routing: Support for RESTful routes with path parameters and wildcards 2. Middleware: Request processing pipeline with before and after handlers 3. Context: Request-scoped context with helper methods for request/response handling 4. Rendering: Support for various response formats (JSON, HTML, etc.) 5. Validation: Request data validation with customizable rules 6. Plugins: Extensions for common web features (CORS, GZIP, Rate Limiting, etc.)
Package znet provides a lightweight and high-performance HTTP web framework.
Index ¶
- Constants
- Variables
- func ClientIP(r *http.Request) (ip string)
- func ClientPublicIP(r *http.Request) string
- func CloseHotRestartFileMd5()deprecated
- func GetIPv(s string) int
- func IPToLong(ip string) (i uint, err error)
- func InNetwork(ip, networkCIDR string) bool
- func IsLocalAddrIP(ip string) bool
- func IsLocalIP(ip net.IP) bool
- func IsValidIP(ip string) (net.IP, bool)
- func JSONRPC(rcvr map[string]interface{}, opts ...func(o *JSONRPCOption)) func(c *Context)
- func LongToIP(i uint) (string, error)
- func LongToNetIP(i uint) (ip net.IP, err error)
- func LongToNetIPv6(i *big.Int) (ip net.IP, err error)
- func MultiplePort(ports []int, change bool) (int, error)
- func NetIPToLong(ip net.IP) (i uint, err error)
- func NetIPv6ToLong(ip net.IP) (*big.Int, error)
- func OnShutdown(done func())
- func ParsePattern(res []string, prefix string) (string, []string)
- func Port(port int, change bool) (newPort int, err error)
- func RegisterRender(invoker ...zdi.PreInvoker) (err error)
- func RemoteIP(r *http.Request) string
- func Run(cb ...func(name, addr string))
- func RunContext(ctx context.Context, cb ...func(name, addr string))
- func Shutdown() error
- func WrapFirstMiddleware(fn Handler) firstHandler
- type ApiData
- type Context
- func (c *Context) Abort(code ...int32)
- func (c *Context) ApiJSON(code int32, msg string, data interface{})
- func (c *Context) Bind(obj interface{}) (err error)
- func (c *Context) BindForm(obj interface{}) error
- func (c *Context) BindJSON(obj interface{}) error
- func (c *Context) BindQuery(obj interface{}) (err error)
- func (c *Context) BindValid(obj interface{}, v map[string]zvalid.Engine) error
- func (c *Context) Byte(code int32, value []byte)
- func (c *Context) CompletionLink(link string) string
- func (c *Context) ContentType(contentText ...string) string
- func (c *Context) DefaultFormOrQuery(key string, def string) string
- func (c *Context) DefaultPostForm(key, def string) string
- func (c *Context) DefaultQuery(key string, def string) string
- func (c *Context) File(path string)
- func (c *Context) FileAttachment(filepath, filename string)
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FormFiles(name string) (files []*multipart.FileHeader, err error)
- func (c *Context) GetAllParam() map[string]string
- func (c *Context) GetAllQuery() url.Values
- func (c *Context) GetAllQueryMaps() map[string]string
- func (c *Context) GetClientIP() string
- func (c *Context) GetCookie(name string) string
- func (c *Context) GetDataRaw() (string, error)
- func (c *Context) GetDataRawBytes() ([]byte, error)
- func (c *Context) GetHeader(key string) string
- func (c *Context) GetJSON(key string) *zjson.Res
- func (c *Context) GetJSONs() (json *zjson.Res, err error)
- func (c *Context) GetParam(key string) string
- func (c *Context) GetPostForm(key string) (string, bool)
- func (c *Context) GetPostFormAll() (value url.Values)
- func (c *Context) GetPostFormArray(key string) ([]string, bool)
- func (c *Context) GetPostFormMap(key string) (map[string]string, bool)
- func (c *Context) GetQuery(key string) (string, bool)
- func (c *Context) GetQueryArray(key string) ([]string, bool)
- func (c *Context) GetQueryMap(key string) (map[string]string, bool)
- func (c *Context) GetReferer() string
- func (c *Context) GetUserAgent() string
- func (c *Context) GetWriter(code int32) io.Writer
- func (c *Context) HTML(code int32, html string)
- func (c *Context) Host(full ...bool) string
- func (c *Context) Injector() zdi.Injector
- func (c *Context) IsAbort() bool
- func (c *Context) IsAjax() bool
- func (c *Context) IsSSE() bool
- func (c *Context) IsWebsocket() bool
- func (c *Context) JSON(code int32, values interface{})
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) MustValue(key string, def ...interface{}) (value interface{})
- func (c *Context) Next() bool
- func (c *Context) ParseMultipartForm(maxMultipartMemory ...int64) error
- func (c *Context) PostFormMap(key string) map[string]string
- func (c *Context) PrevContent() *PrevData
- func (c *Context) QueryMap(key string) map[string]string
- func (c *Context) Redirect(link string, statusCode ...int32)
- func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dist string) error
- func (c *Context) SetContent(data *PrevData)
- func (c *Context) SetContentType(contentType string) *Context
- func (c *Context) SetCookie(name, value string, maxAge ...int)
- func (c *Context) SetHeader(key, value string, only ...bool)
- func (c *Context) SetStatus(code int32) *Context
- func (c *Context) Stream(step func(w io.Writer) bool) bool
- func (c *Context) String(code int32, format string, values ...interface{})
- func (c *Context) Template(code int32, name string, data interface{}, funcMap ...map[string]interface{})
- func (c *Context) Templates(code int32, templates []string, data interface{}, ...)
- func (c *Context) Valid(defRule zvalid.Engine, key string, name ...string) zvalid.Engine
- func (c *Context) ValidForm(defRule zvalid.Engine, key string, name ...string) zvalid.Engine
- func (c *Context) ValidJSON(defRule zvalid.Engine, key string, name ...string) zvalid.Engine
- func (c *Context) ValidParam(defRule zvalid.Engine, key string, name ...string) zvalid.Engine
- func (c *Context) ValidQuery(defRule zvalid.Engine, key string, name ...string) zvalid.Engine
- func (c *Context) ValidRule() zvalid.Engine
- func (c *Context) Value(key string, def ...interface{}) (value interface{}, ok bool)
- func (c *Context) WithValue(key string, value interface{}) *Context
- type Data
- type Engine
- func (e *Engine) AddAddr(addrString string, tlsConfig ...TlsCfg)
- func (e *Engine) Any(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) BindStruct(prefix string, s interface{}, handle ...Handler) error
- func (e *Engine) CONNECT(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) CONNECTAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) Customize(method, path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) DELETE(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) DELETEAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) FindHandle(rw *Context, req *http.Request, requestURL string, applyMiddleware bool) (not bool)
- func (e *Engine) GET(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) GETAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) GenerateURL(method string, routeName string, params map[string]string) (string, error)
- func (e *Engine) GetMode() string
- func (e *Engine) GetTrees() map[string]*Tree
- func (e *Engine) Group(prefix string, groupHandle ...func(e *Engine)) (engine *Engine)
- func (e *Engine) HEAD(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) HEADAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) Handle(method string, path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) HandleNotFound(c *Context, applyMiddleware ...bool)
- func (e *Engine) Injector() zdi.TypeMapper
- func (e *Engine) IsDebug() bool
- func (e *Engine) IsRestarting() bool
- func (e *Engine) LoadHTMLGlob(pattern string)
- func (e *Engine) Match(requestURL string, path string) bool
- func (e *Engine) NewContext(w http.ResponseWriter, req *http.Request) *Context
- func (e *Engine) NotFoundHandler(handler Handler)
- func (e *Engine) OPTIONS(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) OPTIONSAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) PATCH(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) PATCHAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) POST(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) POSTAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) PUT(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) PUTAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) PanicHandler(handler ErrHandlerFunc)deprecated
- func (e *Engine) PreHandler(preHandler Handler)
- func (e *Engine) RegisterRender(invoker ...zdi.PreInvoker) (err error)
- func (e *Engine) Restart() error
- func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (e *Engine) SetAddr(addrString string, tlsConfig ...TlsCfg)
- func (e *Engine) SetCustomMethodField(field string)
- func (e *Engine) SetHTMLTemplate(t *template.Template)deprecated
- func (e *Engine) SetMode(value string)
- func (e *Engine) SetTemplate(v Template)
- func (e *Engine) SetTemplateFuncMap(funcMap template.FuncMap)deprecated
- func (e *Engine) SetTimeout(Timeout time.Duration, WriteTimeout ...time.Duration)
- func (e *Engine) StartUp() []*serverMap
- func (e *Engine) Static(relativePath, root string, moreHandler ...Handler)
- func (e *Engine) StaticFS(relativePath string, fs http.FileSystem, moreHandler ...Handler)
- func (e *Engine) StaticFile(relativePath, filepath string, moreHandler ...Handler)
- func (e *Engine) TRACE(path string, action Handler, moreHandler ...Handler) *Engine
- func (e *Engine) TRACEAndName(path string, action Handler, routeName string) *Engine
- func (e *Engine) Use(middleware ...Handler)
- type ErrHandlerFunc
- type Handler
- type HandlerFunc
- type JSONRPCOption
- type MiddlewareFunc
- type MiddlewareType
- type Node
- type Parameters
- type PrevData
- type Renderer
- type SSE
- type SSEOption
- type Template
- type TemplateOptions
- type TlsCfg
- type Tree
Constants ¶
const ( // DebugMode indicates development mode with verbose logging. DebugMode = "dev" // ProdMode indicates production mode with minimal logging. ProdMode = "prod" // TestMode indicates testing mode. TestMode = "test" // QuietMode indicates a mode with no logging output. QuietMode = "quiet" )
Variables ¶
var ( // RemoteIPHeaders defines the HTTP headers to check for client IP addresses // when the request comes through a proxy or load balancer. RemoteIPHeaders = []string{"X-Forwarded-For", "X-Real-IP", "Cf-Connecting-Ip"} // TrustedProxies defines the IP ranges that are considered trusted proxies. // By default, all IPs are trusted (0.0.0.0/0). TrustedProxies = []string{"0.0.0.0/0"} // LocalNetworks defines the IP ranges that are considered local/private networks. LocalNetworks = []string{"127.0.0.0/8", "10.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "172.0.0.0/8", "192.168.0.0/16", "::1/128", "fc00::/7", "fe80::/10"} )
var ( // ContentTypePlain text ContentTypePlain = "text/plain; charset=utf-8" // ContentTypeHTML html ContentTypeHTML = "text/html; charset=utf-8" // ContentTypeJSON json ContentTypeJSON = "application/json; charset=utf-8" )
var ( // ErrGenerateParameters is returned when generating a route withRequestLog wrong parameters. ErrGenerateParameters = errors.New("params contains wrong parameters") // ErrNotFoundRoute is returned when generating a route that can not find route in tree. ErrNotFoundRoute = errors.New("cannot find route in tree") // ErrNotFoundMethod is returned when generating a route that can not find method in tree. ErrNotFoundMethod = errors.New("cannot find method in tree") // ErrPatternGrammar is returned when generating a route that pattern grammar error. ErrPatternGrammar = errors.New("pattern grammar error") )
var ( // Log Log Log = zlog.New(zlog.ColorTextWrap(zlog.ColorGreen, "[Z] ")) // CloseHotRestart Close Hot Restart CloseHotRestart bool // BindStructDelimiter structure route delimiter BindStructDelimiter = "-" // BindStructSuffix structure route suffix BindStructSuffix = "" )
var Utils = utils{
ContextKey: contextKeyType{},
}
Utils is a global instance of the utils struct that provides utility functions for routing, context handling, and other common operations.
Functions ¶
func ClientPublicIP ¶
ClientPublicIP Return client public IP
func CloseHotRestartFileMd5
deprecated
added in
v0.1.26
func CloseHotRestartFileMd5()
Deprecated: If you need to verify if a program is trustworthy, please implement it yourself. CloseHotRestartFileMd5 CloseHotRestartFileMd5
func IsLocalAddrIP ¶ added in v0.1.42
IsLocalAddrIP checks if the given IP address string belongs to a local network. Returns true if the IP is in one of the defined local networks.
func IsLocalIP ¶ added in v0.1.42
IsLocalIP checks if the given net.IP belongs to a local network. Returns true if the IP is in one of the defined local networks.
func IsValidIP ¶ added in v1.7.19
IsValidIP checks if the given string is a valid IP address (both IPv4 and IPv6)
func JSONRPC ¶ added in v1.4.3
func JSONRPC(rcvr map[string]interface{}, opts ...func(o *JSONRPCOption)) func(c *Context)
JSONRPC creates a handler that processes JSON-RPC requests. It registers the provided receiver objects with the RPC server and returns a handler function that can be used with the router. The handler supports both HTTP and WebSocket transports.
func LongToNetIP ¶ added in v1.1.18
LongToNetIP LongToNetIP
func LongToNetIPv6 ¶ added in v1.1.18
LongToNetIPv6 LongToNetIPv6
func MultiplePort ¶ added in v1.1.8
MultiplePort Check if the multiple port is available, if not, then automatically get an available
func NetIPToLong ¶ added in v1.1.18
NetIPToLong NetIPToLong
func NetIPv6ToLong ¶ added in v1.1.18
NetIPv6ToLong NetIPv6ToLong
func OnShutdown ¶ added in v1.5.2
func OnShutdown(done func())
OnShutdown registers a function to be called when the server shuts down. This is useful for cleanup tasks that should run before the program exits.
func ParsePattern ¶ added in v1.7.19
ParsePattern converts a path pattern into a regular expression and extracts parameter names. It handles various parameter formats including :param, *wildcard, and {name:pattern} syntax.
func Port ¶ added in v1.1.8
Port GetPort Check if the port is available, if not, then automatically get an available
func RegisterRender ¶ added in v1.7.19
func RegisterRender(invoker ...zdi.PreInvoker) (err error)
RegisterRender Register Render
func Run ¶
func Run(cb ...func(name, addr string))
Run starts the HTTP server and begins listening for requests. Optional callback functions are called when each server starts, receiving the server name and address.
func RunContext ¶ added in v1.7.3
RunContext starts all configured servers with a context for cancellation. The provided context can be used to trigger server shutdown. Optional callback functions are called when each server starts.
func Shutdown ¶ added in v1.5.2
func Shutdown() error
Shutdown gracefully stops all running servers. It waits for active connections to complete before shutting down. Returns an error if the shutdown process encounters any issues.
func WrapFirstMiddleware ¶ added in v1.4.9
func WrapFirstMiddleware(fn Handler) firstHandler
WrapFirstMiddleware wraps a handler function to be inserted at the beginning of the middleware chain. This is useful for middleware that must execute before any other middleware.
Types ¶
type ApiData ¶ added in v0.1.36
type ApiData struct {
Data interface{} `json:"data"`
Msg string `json:"msg,omitempty"`
Code int32 `json:"code" example:"200"`
}
ApiData represents a unified API response format with data, message, and status code. It is used for standardizing JSON responses across the application.
type Context ¶
type Context struct {
Writer http.ResponseWriter
Log *zlog.Logger
Request *http.Request
Engine *Engine
Cache *zcache.Table
// contains filtered or unexported fields
}
Context represents the HTTP request and response context. It provides methods for accessing request data, setting response data, and managing the request lifecycle.
func (*Context) Bind ¶ added in v0.0.19
Bind binds the request data to the provided object based on the request method and content type. For GET requests, it binds query parameters. For requests with JSON content type, it binds JSON data. Otherwise, it binds form data. This provides a convenient way to handle different request formats.
func (*Context) BindForm ¶ added in v1.2.0
BindForm binds form data from the request to the provided object. It handles both regular form data and multipart form data, mapping form fields to struct fields based on field tags.
func (*Context) BindJSON ¶ added in v1.2.0
BindJSON binds JSON request body data to the provided object. It reads the raw request body and unmarshals it into the given object.
func (*Context) BindQuery ¶ added in v1.2.0
BindQuery binds URL query parameters to the provided object. It maps query parameters to struct fields based on field tags. Struct fields, slices, and basic types are all handled appropriately.
func (*Context) BindValid ¶ added in v0.1.40
BindValid binds request data to the provided object and validates it using the provided validation rules. It first binds the data using the appropriate method based on request type, then validates the bound data.
func (*Context) Byte ¶ added in v0.0.23
Byte writes raw bytes to the response with the given status code. It automatically detects the content type if possible.
func (*Context) CompletionLink ¶
CompletionLink ensures a URL is absolute by prepending the current host if the provided link is relative.
func (*Context) ContentType ¶ added in v0.0.19
ContentType returns or sets the Content-Type header. If contentText is provided, it sets the Content-Type header. Otherwise, it returns the current Content-Type of the request.
func (*Context) DefaultFormOrQuery ¶ added in v0.0.19
DefaultFormOrQuery Get Form Or Query
func (*Context) DefaultPostForm ¶
DefaultPostForm Get Form Or Default
func (*Context) DefaultQuery ¶
DefaultQuery Get Query Or Default
func (*Context) FileAttachment ¶ added in v1.6.4
FileAttachment serves a file as an attachment with the specified filename. This will prompt the browser to download the file rather than display it.
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile FormFile
func (*Context) FormFiles ¶ added in v1.4.3
func (c *Context) FormFiles(name string) (files []*multipart.FileHeader, err error)
FormFiles Multiple FormFile
func (*Context) GetAllParam ¶
GetAllParam Get the value of all param in the route
func (*Context) GetAllQuery ¶ added in v1.3.1
GetAllQuery Get All Queryst
func (*Context) GetAllQueryMaps ¶ added in v1.3.1
GetAllQueryMaps Get All Queryst Maps
func (*Context) GetClientIP ¶ added in v0.1.20
GetClientIP returns the client's IP address by checking various headers and connection information. It attempts to determine the most accurate client IP, even when behind proxies.
func (*Context) GetCookie ¶
GetCookie returns the value of the cookie with the given name. Returns an empty string if the cookie doesn't exist.
func (*Context) GetDataRaw ¶ added in v0.0.19
GetDataRaw Get Raw Data
func (*Context) GetDataRawBytes ¶ added in v1.6.4
GetDataRawBytes get raw data
func (*Context) GetPostForm ¶
GetPostForm Get PostForm
func (*Context) GetPostFormAll ¶ added in v0.0.19
GetPostFormAll Get PostForm All
func (*Context) GetPostFormArray ¶
GetPostFormArray Get Post FormArray
func (*Context) GetPostFormMap ¶
GetPostFormMap Get PostForm Map
func (*Context) GetQueryArray ¶
GetQueryArray Get Query Array
func (*Context) GetQueryMap ¶ added in v1.2.0
GetQueryMap Get Query Map
func (*Context) GetReferer ¶ added in v0.1.20
GetReferer returns the Referer header of the request, which contains the URL of the page that linked to the current page.
func (*Context) GetUserAgent ¶ added in v0.1.20
GetUserAgent returns the User-Agent header of the request, which identifies the client software originating the request.
func (*Context) Host ¶
Host returns the current host with scheme (http/https). If full is true, it includes the request URL path.
func (*Context) Injector ¶ added in v1.3.0
Injector returns the dependency injection container for this context. This allows handlers to access shared services and dependencies.
func (*Context) IsAbort ¶ added in v1.7.5
IsAbort checks if the request handling has been aborted. It returns true if Abort() has been called, false otherwise.
func (*Context) IsAjax ¶ added in v0.1.30
IsAjax determines if the current request is an AJAX request by checking for the X-Requested-With header with value XMLHttpRequest.
func (*Context) IsSSE ¶ added in v1.4.2
IsSSE determines if the current request is expecting Server-Sent Events by checking if the Accept header contains 'text/event-stream'.
func (*Context) IsWebsocket ¶
IsWebsocket determines if the current request is a WebSocket upgrade request by checking the Connection and Upgrade headers.
func (*Context) MultipartForm ¶
MultipartForm MultipartForm
func (*Context) MustValue ¶ added in v1.4.3
MustValue retrieves data stored in the context by key, with simplified return. If the key doesn't exist and default values are provided, the first default is returned. Unlike Value(), this method only returns the value without the existence flag.
func (*Context) Next ¶
Next executes all remaining middleware in the chain. Returns false if the middleware chain has been stopped with Abort().
func (*Context) ParseMultipartForm ¶ added in v1.3.1
ParseMultipartForm parses multipart form data from the request. An optional maxMultipartMemory parameter can be provided to limit memory usage.
func (*Context) PostFormMap ¶
PostFormMap PostForm Map
func (*Context) PrevContent ¶ added in v0.0.19
PrevContent current output content
func (*Context) SaveUploadedFile ¶
func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dist string) error
SaveUploadedFile Save Uploaded File
func (*Context) SetContent ¶ added in v0.1.21
func (*Context) SetContentType ¶ added in v0.0.26
SetContentType sets the Content-Type header for the response. It returns the context for method chaining.
func (*Context) SetCookie ¶
SetCookie sets an HTTP cookie with the given name and value. Optional maxAge parameter specifies the cookie's max age in seconds (0 = session cookie).
func (*Context) SetHeader ¶
SetHeader sets a response header with the given key and value. If value is empty, the header will be removed.
func (*Context) SetStatus ¶ added in v0.0.19
SetStatus sets the HTTP status code for the response. It returns the context for method chaining.
func (*Context) Stream ¶ added in v1.5.2
Stream sends a streaming response to the client. The provided step function is called repeatedly until it returns false. Each call to step should write data to the provided writer.
func (*Context) String ¶
String writes a formatted string to the response with the given status code. It uses fmt.Sprintf-style formatting with the provided values.
func (*Context) Template ¶
func (c *Context) Template(code int32, name string, data interface{}, funcMap ...map[string]interface{})
Template export tpl
func (*Context) Valid ¶ added in v0.0.20
Valid validates data from multiple sources in order: JSON/form data -> query parameters -> route parameters. It tries to find the value in each source and applies the provided validation rules to the first non-empty value found. Optional name parameter can be provided for error messages.
func (*Context) ValidForm ¶ added in v0.0.20
ValidForm gets and validates form data. It retrieves the form field value by key and applies the provided validation rules. Optional name parameter can be provided for error messages.
func (*Context) ValidJSON ¶ added in v0.0.20
ValidJSON gets and validates JSON data. It retrieves the JSON value by key path and applies the provided validation rules. Optional name parameter can be provided for error messages.
func (*Context) ValidParam ¶ added in v0.0.20
ValidParam gets and validates route parameters. It retrieves the parameter value by key and applies the provided validation rules. Optional name parameter can be provided for error messages.
func (*Context) ValidQuery ¶ added in v0.0.20
ValidQuery gets and validates URL query parameters. It retrieves the query parameter value by key and applies the provided validation rules. Optional name parameter can be provided for error messages.
func (*Context) ValidRule ¶ added in v0.0.20
ValidRule creates and returns a new validation engine. This is a convenience method to start building validation rules for request data.
type Data ¶ added in v0.0.19
type Data map[string]interface{}
Data is a convenience type for map[string]interface{} used for template data and other data structures throughout the framework.
type Engine ¶
type Engine struct {
BindStructCase func(string) string
Log *zlog.Logger
BindStructSuffix string
BindTag string
BindStructDelimiter string
MaxMultipartMemory int64
MaxRequestBodySize int64
ShowFavicon bool
AllowQuerySemicolons bool
// contains filtered or unexported fields
}
Engine is the core of the web framework, providing HTTP routing and server functionality. It manages routes, middleware, templates, and server configuration.
func New ¶
New creates and initializes a new Engine instance. An optional serverName can be provided to identify this server in logs. The returned Engine is configured with default settings and ready to define routes.
func Server ¶
Server retrieves an existing Engine instance by name. Returns the Engine and a boolean indicating if it was found.
func (*Engine) AddAddr ¶ added in v0.0.19
AddAddr adds an additional address for the server to listen on. This allows the server to listen on multiple ports or interfaces.
func (*Engine) Any ¶
Any registers a handler for all HTTP methods on the given path. This is a shortcut for registering the same handler under all methods.
func (*Engine) BindStruct ¶ added in v0.1.42
BindStruct Bind Struct
func (*Engine) CONNECT ¶ added in v0.1.64
CONNECT registers a handler for HTTP CONNECT requests on the given path.
func (*Engine) CONNECTAndName ¶ added in v0.1.64
CONNECTAndName registers a named handler for HTTP CONNECT requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) Customize ¶ added in v0.0.19
Customize registers a handler for a custom HTTP method on the given path. The method string is converted to uppercase before registration.
func (*Engine) DELETEAndName ¶
DELETEAndName registers a named handler for HTTP DELETE requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) FindHandle ¶ added in v0.0.19
func (e *Engine) FindHandle(rw *Context, req *http.Request, requestURL string, applyMiddleware bool) (not bool)
FindHandle searches for a handler matching the request URL and executes it if found. It returns true if a handler was found and executed, false otherwise.
func (*Engine) GETAndName ¶
GETAndName registers a named handler for HTTP GET requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) GenerateURL ¶
func (e *Engine) GenerateURL(method string, routeName string, params map[string]string) (string, error)
GenerateURL generates a URL for a named route with the given parameters. This is useful for creating links to other routes in your application. It returns an error if the route name doesn't exist or if required parameters are missing.
func (*Engine) GetMode ¶ added in v1.3.1
GetMode returns the current server operating mode as a string.
func (*Engine) GetTrees ¶
GetTrees returns the internal routing trees for all HTTP methods. This is primarily used for debugging and testing purposes.
func (*Engine) Group ¶
Group creates a new router group with the given prefix. All routes registered within the group will have the prefix prepended. This is useful for organizing routes by feature or area of responsibility.
func (*Engine) HEADAndName ¶
HEADAndName registers a named handler for HTTP HEAD requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) Handle ¶
Handle registers a new handler for the specified HTTP method and path. This is the core routing function that all other HTTP method functions use internally.
func (*Engine) HandleNotFound ¶
HandleNotFound is a public wrapper around handleNotFound. It allows external code to trigger a not found response for a context.
func (*Engine) Injector ¶ added in v1.3.0
func (e *Engine) Injector() zdi.TypeMapper
Injector returns the dependency injection container used by this Engine. It can be used to register services for use in handlers.
func (*Engine) IsRestarting ¶ added in v1.7.19
IsRestarting returns whether the server is currently restarting
func (*Engine) LoadHTMLGlob ¶ added in v1.1.3
LoadHTMLGlob Load Glob HTML LoadHTMLGlob loads HTML templates from the specified glob pattern. It parses the templates and makes them available for rendering in handlers.
func (*Engine) Match ¶
Match checks if the request URL matches the route pattern. This is used internally for routing but can also be used to test if a URL would match a pattern.
func (*Engine) NewContext ¶ added in v0.1.34
NewContext creates a new Context instance for handling a request. This is used when you need to manually create a context outside the normal request flow.
func (*Engine) NotFoundHandler ¶ added in v0.0.26
NotFoundHandler sets a custom handler for 404 Not Found responses. This handler is called when no route matches the request URL.
func (*Engine) OPTIONSAndName ¶
OPTIONSAndName registers a named handler for HTTP OPTIONS requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) PATCHAndName ¶
PATCHAndName registers a named handler for HTTP PATCH requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) POSTAndName ¶
POSTAndName registers a named handler for HTTP POST requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) PUTAndName ¶
PUTAndName registers a named handler for HTTP PUT requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
func (*Engine) PanicHandler
deprecated
func (e *Engine) PanicHandler(handler ErrHandlerFunc)
Deprecated: please use znet.Recovery(func(c *Context, err error) {}) PanicHandler is used for handling panics
func (*Engine) PreHandler ¶ added in v0.1.53
PreHandler sets a handler that runs before any route handler. This is useful for global preprocessing of all requests.
func (*Engine) RegisterRender ¶ added in v1.7.19
func (e *Engine) RegisterRender(invoker ...zdi.PreInvoker) (err error)
RegisterRender Register Render
func (*Engine) ServeHTTP ¶
func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements the http.Handler interface. This is the main entry point for handling HTTP requests in the framework.
func (*Engine) SetAddr ¶
SetAddr sets the address for the server to listen on. Optional TLS configuration can be provided for HTTPS support.
func (*Engine) SetCustomMethodField ¶
SetCustomMethodField sets the field name used for HTTP method overriding. This allows clients to use methods like PUT/DELETE in environments that only support GET/POST.
func (*Engine) SetHTMLTemplate
deprecated
added in
v1.1.10
func (*Engine) SetMode ¶
SetMode sets the server's operating mode (dev, prod, test, or quiet). This affects logging verbosity and other runtime behaviors.
func (*Engine) SetTemplate ¶ added in v1.4.8
func (*Engine) SetTemplateFuncMap
deprecated
added in
v1.1.3
func (*Engine) SetTimeout ¶
SetTimeout sets the read timeout and optionally the write timeout for the HTTP server. These timeouts help prevent slow client attacks.
func (*Engine) StartUp ¶ added in v1.1.15
func (e *Engine) StartUp() []*serverMap
StartUp initializes and starts the HTTP server(s) for this Engine. It configures all servers according to the Engine settings and begins listening on all configured addresses. Returns the server instances that were started.
func (*Engine) Static ¶
Static serves files from the given root directory at the specified path. This is a convenience wrapper around StaticFS with http.Dir.
func (*Engine) StaticFS ¶
func (e *Engine) StaticFS(relativePath string, fs http.FileSystem, moreHandler ...Handler)
StaticFS serves files from the given file system at the specified path. It registers GET, HEAD, and OPTIONS handlers for the specified path and its subdirectories.
func (*Engine) StaticFile ¶
StaticFile serves a single file at the specified path. It registers GET, HEAD, and OPTIONS handlers for the specified path.
func (*Engine) TRACE ¶ added in v0.1.64
TRACE registers a handler for HTTP TRACE requests on the given path.
func (*Engine) TRACEAndName ¶ added in v0.1.64
TRACEAndName registers a named handler for HTTP TRACE requests on the given path. The route name can be used later with GenerateURL to generate URLs for this route.
type ErrHandlerFunc ¶ added in v1.3.0
ErrHandlerFunc defines the error handler function signature. It receives both the context and the error that occurred.
type Handler ¶ added in v1.3.0
type Handler interface{}
Handler is the interface for HTTP request handlers. It can be a function with various signatures that the framework adapts to.
func Recovery ¶ added in v0.1.37
func Recovery(handler ErrHandlerFunc) Handler
Recovery is a middleware that recovers from panics anywhere in the chain
func RewriteErrorHandler ¶ added in v1.3.0
func RewriteErrorHandler(handler ErrHandlerFunc) Handler
RewriteErrorHandler rewrite error handler
type HandlerFunc ¶
type HandlerFunc func(c *Context)
HandlerFunc is the legacy handler function signature. It receives a context pointer but doesn't return an error.
type JSONRPCOption ¶ added in v1.4.3
type JSONRPCOption struct {
DisabledHTTP bool // Disables HTTP method handling, only processes RPC calls
Debug bool // Enables debug mode with additional logging and method inspection
}
JSONRPCOption defines configuration options for the JSON-RPC handler.
type MiddlewareFunc ¶
MiddlewareFunc defines the middleware function signature. It receives both the context and the next handler in the chain.
type MiddlewareType ¶
type MiddlewareType Handler
MiddlewareType is a public type alias for Handler used in middleware contexts.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node represents a single node in the routing tree. Each node can have a handler function and child nodes. Nodes can represent static path segments or pattern parameters.
func NewNode ¶
NewNode creates a new tree node with the given key and depth. The key represents the path segment this node matches.
func (*Node) Handle ¶ added in v1.4.10
func (t *Node) Handle() handlerFn
Handle returns the handler function associated with this node.
type Parameters ¶
type Parameters struct {
// contains filtered or unexported fields
}
Parameters stores route-related information during request processing.
type PrevData ¶ added in v0.1.21
PrevData stores response information before it's sent to the client. It includes status code, content type, and the actual content bytes.
type Renderer ¶ added in v1.7.18
Renderer is the interface that wraps the Content method. Any type implementing this interface can be used to render responses.
type SSE ¶ added in v1.4.2
type SSE struct {
Comment []byte
// contains filtered or unexported fields
}
SSE represents a Server-Sent Events connection. It handles the event stream between the server and client.
func NewSSE ¶ added in v1.4.2
NewSSE creates a new Server-Sent Events connection from an HTTP context. It configures the connection based on the provided options and starts the event loop.
func (*SSE) Done ¶ added in v1.4.2
func (s *SSE) Done() <-chan struct{}
Done returns a channel that's closed when the SSE connection is terminated. This can be used to detect when the client disconnects.
func (*SSE) LastEventID ¶ added in v1.4.2
LastEventID returns the ID of the last event sent over this SSE connection.
type SSEOption ¶ added in v1.4.2
type SSEOption struct {
RetryTime int // Client reconnection time in milliseconds
HeartbeatsTime int // Heartbeat interval in seconds
}
SSEOption defines configuration options for an SSE connection.
type TemplateOptions ¶ added in v1.4.8
type TlsCfg ¶ added in v0.0.19
type TlsCfg struct {
HTTPProcessing interface{}
Config *tls.Config
Cert string
Key string
HTTPAddr string
}
TlsCfg holds TLS configuration for secure HTTP connections.
type Tree ¶
type Tree struct {
// contains filtered or unexported fields
}
Tree represents a radix tree for HTTP routing. It stores routes and their handlers in an efficient tree structure for fast URL matching and parameter extraction.
func NewTree ¶
func NewTree() *Tree
NewTree creates a new routing tree with a root node. The root node represents the '/' path and serves as the starting point for all route matching operations.
func (*Tree) Add ¶
func (t *Tree) Add(e *Engine, path string, handle handlerFn, middleware ...handlerFn) (currentNode *Node)
Add registers a new path with its handler and middleware in the routing tree. It splits the path into segments and creates nodes as needed for each segment. Middleware functions are attached to the leaf node or root node as appropriate. Returns the leaf node that was created or updated, which can be used for further configuration.
func (*Tree) Find ¶
Find searches for nodes that match the given pattern in the routing tree. If isRegex is true, it will return all nodes that match the pattern as a prefix, which is useful for finding all routes under a specific path. Otherwise, it will only return nodes that exactly match the pattern. Returns a slice of matching nodes, which may be empty if no matches are found.