znet

package
v1.7.20 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2025 License: MIT Imports: 47 Imported by: 27

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

View Source
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

View Source
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"}
)
View Source
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"
)
View Source
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")
)
View Source
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 = ""
)
View Source
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 ClientIP

func ClientIP(r *http.Request) (ip string)

ClientIP Return client IP

func ClientPublicIP

func ClientPublicIP(r *http.Request) string

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 GetIPv added in v1.1.18

func GetIPv(s string) int

GetIPv GetIPv

func IPToLong added in v1.1.18

func IPToLong(ip string) (i uint, err error)

IPToLong IPToLong

func InNetwork added in v1.1.18

func InNetwork(ip, networkCIDR string) bool

InNetwork InNetwork

func IsLocalAddrIP added in v0.1.42

func IsLocalAddrIP(ip string) bool

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

func IsLocalIP(ip net.IP) bool

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

func IsValidIP(ip string) (net.IP, bool)

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 LongToIP added in v1.1.18

func LongToIP(i uint) (string, error)

LongToIP LongToIP

func LongToNetIP added in v1.1.18

func LongToNetIP(i uint) (ip net.IP, err error)

LongToNetIP LongToNetIP

func LongToNetIPv6 added in v1.1.18

func LongToNetIPv6(i *big.Int) (ip net.IP, err error)

LongToNetIPv6 LongToNetIPv6

func MultiplePort added in v1.1.8

func MultiplePort(ports []int, change bool) (int, error)

MultiplePort Check if the multiple port is available, if not, then automatically get an available

func NetIPToLong added in v1.1.18

func NetIPToLong(ip net.IP) (i uint, err error)

NetIPToLong NetIPToLong

func NetIPv6ToLong added in v1.1.18

func NetIPv6ToLong(ip net.IP) (*big.Int, error)

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

func ParsePattern(res []string, prefix string) (string, []string)

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

func Port(port int, change bool) (newPort int, err error)

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 RemoteIP

func RemoteIP(r *http.Request) string

RemoteIP Remote IP

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

func RunContext(ctx context.Context, cb ...func(name, addr string))

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) Abort

func (c *Context) Abort(code ...int32)

Abort stop executing subsequent handlers

func (*Context) ApiJSON added in v0.1.36

func (c *Context) ApiJSON(code int32, msg string, data interface{})

ApiJSON ApiJSON

func (*Context) Bind added in v0.0.19

func (c *Context) Bind(obj interface{}) (err error)

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

func (c *Context) BindForm(obj interface{}) error

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

func (c *Context) BindJSON(obj interface{}) error

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

func (c *Context) BindQuery(obj interface{}) (err error)

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

func (c *Context) BindValid(obj interface{}, v map[string]zvalid.Engine) error

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

func (c *Context) Byte(code int32, value []byte)

Byte writes raw bytes to the response with the given status code. It automatically detects the content type if possible.

func (c *Context) CompletionLink(link string) string

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

func (c *Context) ContentType(contentText ...string) string

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

func (c *Context) DefaultFormOrQuery(key string, def string) string

DefaultFormOrQuery Get Form Or Query

func (*Context) DefaultPostForm

func (c *Context) DefaultPostForm(key, def string) string

DefaultPostForm Get Form Or Default

func (*Context) DefaultQuery

func (c *Context) DefaultQuery(key string, def string) string

DefaultQuery Get Query Or Default

func (*Context) File

func (c *Context) File(path string)

func (*Context) FileAttachment added in v1.6.4

func (c *Context) FileAttachment(filepath, filename string)

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

func (c *Context) GetAllParam() map[string]string

GetAllParam Get the value of all param in the route

func (*Context) GetAllQuery added in v1.3.1

func (c *Context) GetAllQuery() url.Values

GetAllQuery Get All Queryst

func (*Context) GetAllQueryMaps added in v1.3.1

func (c *Context) GetAllQueryMaps() map[string]string

GetAllQueryMaps Get All Queryst Maps

func (*Context) GetClientIP added in v0.1.20

func (c *Context) GetClientIP() string

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

func (c *Context) GetCookie(name string) string

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

func (c *Context) GetDataRaw() (string, error)

GetDataRaw Get Raw Data

func (*Context) GetDataRawBytes added in v1.6.4

func (c *Context) GetDataRawBytes() ([]byte, error)

GetDataRawBytes get raw data

func (*Context) GetHeader

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

GetHeader returns the value of the specified request header.

func (*Context) GetJSON added in v0.0.19

func (c *Context) GetJSON(key string) *zjson.Res

GetJSON Get JSON

func (*Context) GetJSONs added in v0.0.19

func (c *Context) GetJSONs() (json *zjson.Res, err error)

GetJSONs Get JSONs

func (*Context) GetParam

func (c *Context) GetParam(key string) string

GetParam Get the value of the param inside the route

func (*Context) GetPostForm

func (c *Context) GetPostForm(key string) (string, bool)

GetPostForm Get PostForm

func (*Context) GetPostFormAll added in v0.0.19

func (c *Context) GetPostFormAll() (value url.Values)

GetPostFormAll Get PostForm All

func (*Context) GetPostFormArray

func (c *Context) GetPostFormArray(key string) ([]string, bool)

GetPostFormArray Get Post FormArray

func (*Context) GetPostFormMap

func (c *Context) GetPostFormMap(key string) (map[string]string, bool)

GetPostFormMap Get PostForm Map

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery Get Query

func (*Context) GetQueryArray

func (c *Context) GetQueryArray(key string) ([]string, bool)

GetQueryArray Get Query Array

func (*Context) GetQueryMap added in v1.2.0

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

GetQueryMap Get Query Map

func (*Context) GetReferer added in v0.1.20

func (c *Context) GetReferer() string

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

func (c *Context) GetUserAgent() string

GetUserAgent returns the User-Agent header of the request, which identifies the client software originating the request.

func (*Context) GetWriter added in v1.7.19

func (c *Context) GetWriter(code int32) io.Writer

GetWriter get render writer

func (*Context) HTML

func (c *Context) HTML(code int32, html string)

HTML export html

func (*Context) Host

func (c *Context) Host(full ...bool) string

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

func (c *Context) Injector() zdi.Injector

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

func (c *Context) IsAbort() bool

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

func (c *Context) IsAjax() bool

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

func (c *Context) IsSSE() bool

IsSSE determines if the current request is expecting Server-Sent Events by checking if the Accept header contains 'text/event-stream'.

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

IsWebsocket determines if the current request is a WebSocket upgrade request by checking the Connection and Upgrade headers.

func (*Context) JSON

func (c *Context) JSON(code int32, values interface{})

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm MultipartForm

func (*Context) MustValue added in v1.4.3

func (c *Context) MustValue(key string, def ...interface{}) (value interface{})

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

func (c *Context) Next() bool

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

func (c *Context) ParseMultipartForm(maxMultipartMemory ...int64) error

ParseMultipartForm parses multipart form data from the request. An optional maxMultipartMemory parameter can be provided to limit memory usage.

func (*Context) PostFormMap

func (c *Context) PostFormMap(key string) map[string]string

PostFormMap PostForm Map

func (*Context) PrevContent added in v0.0.19

func (c *Context) PrevContent() *PrevData

PrevContent current output content

func (*Context) QueryMap added in v1.2.0

func (c *Context) QueryMap(key string) map[string]string

QueryMap Get Query Map

func (*Context) Redirect

func (c *Context) Redirect(link string, statusCode ...int32)

Redirect Redirect

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 (c *Context) SetContent(data *PrevData)

func (*Context) SetContentType added in v0.0.26

func (c *Context) SetContentType(contentType string) *Context

SetContentType sets the Content-Type header for the response. It returns the context for method chaining.

func (*Context) SetCookie

func (c *Context) SetCookie(name, value string, maxAge ...int)

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

func (c *Context) SetHeader(key, value string, only ...bool)

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

func (c *Context) SetStatus(code int32) *Context

SetStatus sets the HTTP status code for the response. It returns the context for method chaining.

func (*Context) Stream added in v1.5.2

func (c *Context) Stream(step func(w io.Writer) bool) bool

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

func (c *Context) String(code int32, format string, values ...interface{})

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) Templates added in v0.1.47

func (c *Context) Templates(code int32, templates []string, data interface{}, funcMap ...map[string]interface{})

func (*Context) Valid added in v0.0.20

func (c *Context) Valid(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

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

func (c *Context) ValidForm(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

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

func (c *Context) ValidJSON(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

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

func (c *Context) ValidParam(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

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

func (c *Context) ValidQuery(defRule zvalid.Engine, key string, name ...string) zvalid.Engine

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

func (c *Context) ValidRule() zvalid.Engine

ValidRule creates and returns a new validation engine. This is a convenience method to start building validation rules for request data.

func (*Context) Value added in v0.0.19

func (c *Context) Value(key string, def ...interface{}) (value interface{}, ok bool)

Value retrieves data stored in the context by key. It returns the value and a boolean indicating if the key exists. If the key doesn't exist and default values are provided, the first default is returned.

func (*Context) WithValue added in v0.0.19

func (c *Context) WithValue(key string, value interface{}) *Context

WithValue stores a key-value pair in the context for sharing data between middleware and handlers. Returns the context for chaining.

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

func New(serverName ...string) *Engine

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

func Server(serverName ...string) (engine *Engine, ok bool)

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

func (e *Engine) AddAddr(addrString string, tlsConfig ...TlsCfg)

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

func (e *Engine) Any(path string, action Handler, moreHandler ...Handler) *Engine

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

func (e *Engine) BindStruct(prefix string, s interface{}, handle ...Handler) error

BindStruct Bind Struct

func (*Engine) CONNECT added in v0.1.64

func (e *Engine) CONNECT(path string, action Handler, moreHandler ...Handler) *Engine

CONNECT registers a handler for HTTP CONNECT requests on the given path.

func (*Engine) CONNECTAndName added in v0.1.64

func (e *Engine) CONNECTAndName(path string, action Handler, routeName string) *Engine

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

func (e *Engine) Customize(method, path string, action Handler, moreHandler ...Handler) *Engine

Customize registers a handler for a custom HTTP method on the given path. The method string is converted to uppercase before registration.

func (*Engine) DELETE

func (e *Engine) DELETE(path string, action Handler, moreHandler ...Handler) *Engine

DELETE registers a handler for HTTP DELETE requests on the given path.

func (*Engine) DELETEAndName

func (e *Engine) DELETEAndName(path string, action Handler, routeName string) *Engine

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) GET

func (e *Engine) GET(path string, action Handler, moreHandler ...Handler) *Engine

GET registers a handler for HTTP GET requests on the given path.

func (*Engine) GETAndName

func (e *Engine) GETAndName(path string, action Handler, routeName string) *Engine

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

func (e *Engine) GetMode() string

GetMode returns the current server operating mode as a string.

func (*Engine) GetTrees

func (e *Engine) GetTrees() map[string]*Tree

GetTrees returns the internal routing trees for all HTTP methods. This is primarily used for debugging and testing purposes.

func (*Engine) Group

func (e *Engine) Group(prefix string, groupHandle ...func(e *Engine)) (engine *Engine)

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) HEAD

func (e *Engine) HEAD(path string, action Handler, moreHandler ...Handler) *Engine

HEAD registers a handler for HTTP HEAD requests on the given path.

func (*Engine) HEADAndName

func (e *Engine) HEADAndName(path string, action Handler, routeName string) *Engine

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

func (e *Engine) Handle(method string, path string, action Handler, moreHandler ...Handler) *Engine

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

func (e *Engine) HandleNotFound(c *Context, applyMiddleware ...bool)

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) IsDebug

func (e *Engine) IsDebug() bool

IsDebug returns true if the server is running in debug mode.

func (*Engine) IsRestarting added in v1.7.19

func (e *Engine) IsRestarting() bool

IsRestarting returns whether the server is currently restarting

func (*Engine) LoadHTMLGlob added in v1.1.3

func (e *Engine) LoadHTMLGlob(pattern string)

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

func (e *Engine) Match(requestURL string, path string) bool

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

func (e *Engine) NewContext(w http.ResponseWriter, req *http.Request) *Context

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

func (e *Engine) NotFoundHandler(handler Handler)

NotFoundHandler sets a custom handler for 404 Not Found responses. This handler is called when no route matches the request URL.

func (*Engine) OPTIONS

func (e *Engine) OPTIONS(path string, action Handler, moreHandler ...Handler) *Engine

OPTIONS registers a handler for HTTP OPTIONS requests on the given path.

func (*Engine) OPTIONSAndName

func (e *Engine) OPTIONSAndName(path string, action Handler, routeName string) *Engine

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) PATCH

func (e *Engine) PATCH(path string, action Handler, moreHandler ...Handler) *Engine

PATCH registers a handler for HTTP PATCH requests on the given path.

func (*Engine) PATCHAndName

func (e *Engine) PATCHAndName(path string, action Handler, routeName string) *Engine

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) POST

func (e *Engine) POST(path string, action Handler, moreHandler ...Handler) *Engine

POST registers a handler for HTTP POST requests on the given path.

func (*Engine) POSTAndName

func (e *Engine) POSTAndName(path string, action Handler, routeName string) *Engine

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) PUT

func (e *Engine) PUT(path string, action Handler, moreHandler ...Handler) *Engine

PUT registers a handler for HTTP PUT requests on the given path.

func (*Engine) PUTAndName

func (e *Engine) PUTAndName(path string, action Handler, routeName string) *Engine

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

func (e *Engine) PreHandler(preHandler Handler)

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) Restart added in v0.0.22

func (e *Engine) Restart() error

Restart triggers a server process restart

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

func (e *Engine) SetAddr(addrString string, tlsConfig ...TlsCfg)

SetAddr sets the address for the server to listen on. Optional TLS configuration can be provided for HTTPS support.

func (*Engine) SetCustomMethodField

func (e *Engine) SetCustomMethodField(field string)

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 (e *Engine) SetHTMLTemplate(t *template.Template)

Deprecated: please use SetTemplate() SetHTMLTemplate Set HTML Template

func (*Engine) SetMode

func (e *Engine) SetMode(value string)

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 (e *Engine) SetTemplate(v Template)

func (*Engine) SetTemplateFuncMap deprecated added in v1.1.3

func (e *Engine) SetTemplateFuncMap(funcMap template.FuncMap)

Deprecated: please use SetTemplate() SetTemplateFuncMap Set Template Func

func (*Engine) SetTimeout

func (e *Engine) SetTimeout(Timeout time.Duration, WriteTimeout ...time.Duration)

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

func (e *Engine) Static(relativePath, root string, moreHandler ...Handler)

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

func (e *Engine) StaticFile(relativePath, filepath string, moreHandler ...Handler)

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

func (e *Engine) TRACE(path string, action Handler, moreHandler ...Handler) *Engine

TRACE registers a handler for HTTP TRACE requests on the given path.

func (*Engine) TRACEAndName added in v0.1.64

func (e *Engine) TRACEAndName(path string, action Handler, routeName string) *Engine

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.

func (*Engine) Use

func (e *Engine) Use(middleware ...Handler)

Use adds global middleware to the engine. These middleware functions will be executed for every request before route-specific middleware.

type ErrHandlerFunc added in v1.3.0

type ErrHandlerFunc func(c *Context, err error)

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

type MiddlewareFunc func(c *Context, fn Handler)

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

func NewNode(key string, depth int) *Node

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.

func (*Node) Path added in v1.4.10

func (t *Node) Path() string

Path returns the full path that this node represents.

func (*Node) Value added in v1.4.10

func (t *Node) Value() interface{}

Value returns the value associated with this node.

func (*Node) WithValue added in v1.4.10

func (t *Node) WithValue(v interface{}) *Node

WithValue associates a value with this node and returns the node. This allows for method chaining when building the tree.

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

type PrevData struct {
	Code    *zutil.Int32
	Type    string
	Content []byte
}

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

type Renderer interface {
	Content(c *Context) (content []byte)
}

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

func NewSSE(c *Context, opts ...func(lastID string, opts *SSEOption)) *SSE

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

func (s *SSE) LastEventID() string

LastEventID returns the ID of the last event sent over this SSE connection.

func (*SSE) Push added in v1.4.2

func (s *SSE) Push()

func (*SSE) Send added in v1.4.2

func (s *SSE) Send(id string, data string, event ...string) error

func (*SSE) SendByte added in v1.4.2

func (s *SSE) SendByte(id string, data []byte, event ...string) error

SendByte sends raw byte data as an SSE event. It allows specifying an event ID and optional event type.

func (*SSE) Stop added in v1.4.2

func (s *SSE) Stop()

Stop terminates the SSE connection. This will close the event stream and release associated resources.

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 Template added in v1.4.8

type Template interface {
	Load() error
	Render(io.Writer, string, interface{}, ...string) error
}

type TemplateOptions added in v1.4.8

type TemplateOptions struct {
	Extension  string
	Layout     string
	DelimLeft  string
	DelimRight string
	Reload     bool
	Debug      bool
}

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

func (t *Tree) Find(pattern string, isRegex bool) (nodes []*Node)

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.

Directories

Path Synopsis
Package session provides in-memory session storage implementation.
Package session provides in-memory session storage implementation.

Jump to

Keyboard shortcuts

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