Documentation
¶
Index ¶
- Constants
- Variables
- func Call(ctx *Ctx, c *core.ServiceDiscoveryClient, req proto.Message, rsp proto.Message) error
- type App
- func (p *App) AcquireCtx(ctx *fasthttp.RequestCtx) *Ctx
- func (p *App) AddRoute(r *Route, opts ...RouteOption)
- func (p *App) AddRoutes(rs []*Route, opts ...RouteOption)
- func (p *App) Connect(path string, handler HandlerFunc, opts ...RouteOption)
- func (app *App) DELETE(path string, handlers ...HandlerFunc) error
- func (p *App) Delete(path string, handler HandlerFunc, opts ...RouteOption)
- func (p *App) ErrorHandler(c *fasthttp.RequestCtx, err error)
- func (app *App) GET(path string, handlers ...HandlerFunc) error
- func (p *App) Get(path string, handler HandlerFunc, opts ...RouteOption)
- func (app *App) Group(prefix string, handlers ...HandlerFunc) *Group
- func (app *App) HEAD(path string, handlers ...HandlerFunc) error
- func (p *App) Handle(method, path string, handler HandlerFunc, opts ...RouteOption)
- func (p *App) Handler(c *fasthttp.RequestCtx)
- func (p *App) Head(path string, handler HandlerFunc, opts ...RouteOption)
- func (p *App) Hooks() *Hooks
- func (p *App) ListenAndServe(port int, handlers ...ListenHandler) (err error)
- func (app *App) OPTIONS(path string, handlers ...HandlerFunc) error
- func (p *App) OnListen(logic func(ListenData) error)
- func (p *App) OnRoute(route func(*Route) error)
- func (p *App) OnShutdown(logic func(ListenData))
- func (p *App) Options(path string, handler HandlerFunc, opts ...RouteOption)
- func (app *App) PATCH(path string, handlers ...HandlerFunc) error
- func (app *App) POST(path string, handlers ...HandlerFunc) error
- func (app *App) PUT(path string, handlers ...HandlerFunc) error
- func (p *App) Patch(path string, handler HandlerFunc, opts ...RouteOption)
- func (p *App) Post(path string, handler HandlerFunc, opts ...RouteOption)
- func (p *App) Put(path string, handler HandlerFunc, opts ...RouteOption)
- func (p *App) ReleaseCtx(ctx *Ctx)
- func (app *App) ServeHTTP(ctx *fasthttp.RequestCtx)
- func (p *App) ToHandlerFunc(logic any) HandlerFunc
- func (p *App) Trace(path string, handler HandlerFunc, opts ...RouteOption)
- func (app *App) Use(handlers ...HandlerFunc)
- type BaseResponse
- type Client
- type Config
- type Ctx
- func (p *Ctx) AllParams() map[string]string
- func (p *Ctx) AllQueries() map[string]string
- func (p *Ctx) Body() []byte
- func (p *Ctx) BodyEmpty() bool
- func (p *Ctx) BodyParser(o any) (err error)
- func (p *Ctx) ClearCookie(name string, path string)
- func (p *Ctx) Context() *fasthttp.RequestCtx
- func (p *Ctx) Cookie(name string) string
- func (p *Ctx) FormFile(key string) (*multipart.FileHeader, error)
- func (p *Ctx) GetLocal(key string) any
- func (p *Ctx) Header(key string) string
- func (p *Ctx) IsBodyStream() bool
- func (p *Ctx) Method() string
- func (p *Ctx) MultipartForm() (*multipart.Form, error)
- func (p *Ctx) Next() error
- func (p *Ctx) Param(key string) string
- func (p *Ctx) Path() string
- func (p *Ctx) Query(key string) string
- func (p *Ctx) QueryBool(key string, defaultValue ...bool) bool
- func (p *Ctx) QueryInt(key string, defaultValue ...int) int
- func (p *Ctx) Reset()
- func (p *Ctx) SaveFile(fileHeader *multipart.FileHeader, path string) error
- func (p *Ctx) Send(body []byte)
- func (p *Ctx) SendJson(o any) error
- func (p *Ctx) SendStatus(status int)
- func (p *Ctx) SendString(s string)
- func (p *Ctx) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (p *Ctx) SetHeader(key string, value string)
- func (p *Ctx) SetLocal(key string, value any)
- func (p *Ctx) SetParam(key, value string)
- func (p *Ctx) SetTraceID(traceID ...string)
- func (p *Ctx) TraceID() string
- type Group
- func (g *Group) DELETE(path string, handlers ...HandlerFunc) error
- func (g *Group) GET(path string, handlers ...HandlerFunc) error
- func (g *Group) Group(prefix string, handlers ...HandlerFunc) *Group
- func (g *Group) HEAD(path string, handlers ...HandlerFunc) error
- func (g *Group) OPTIONS(path string, handlers ...HandlerFunc) error
- func (g *Group) PATCH(path string, handlers ...HandlerFunc) error
- func (g *Group) POST(path string, handlers ...HandlerFunc) error
- func (g *Group) PUT(path string, handlers ...HandlerFunc) error
- func (g *Group) Use(handlers ...HandlerFunc) *Group
- type HandlerFunc
- type Hooks
- type ListenData
- type ListenHandler
- type MatchResult
- type ParamConstraint
- type RecoverConfig
- type Route
- type RouteNode
- type RouteOption
- type RouteParam
- type RouteType
- type Router
- type SearchResult
- type SearchTree
Constants ¶
const ( HeaderAuthorization = "Authorization" HeaderProxyAuthenticate = "Proxy-Authenticate" HeaderProxyAuthorization = "Proxy-Authorization" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderAge = "Age" HeaderCacheControl = "Cache-Control" HeaderClearSiteData = "Clear-Site-Data" HeaderExpires = "Expires" HeaderPragma = "Pragma" HeaderWarning = "Warning" HeaderAcceptCH = "Accept-CH" HeaderAcceptCHLifetime = "Accept-CH-Lifetime" HeaderContentDPR = "Content-DPR" HeaderDPR = "DPR" HeaderEarlyData = "Early-Data" HeaderSaveData = "Save-Data" HeaderViewportWidth = "Viewport-Width" HeaderWidth = "Width" HeaderETag = "ETag" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderLastModified = "Last-Modified" HeaderVary = "Vary" HeaderConnection = "Connection" HeaderKeepAlive = "Keep-Alive" HeaderAccept = "Accept" HeaderAcceptCharset = "Accept-Charset" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" HeaderCookie = "Cookie" HeaderExpect = "Expect" HeaderMaxForwards = "Max-Forwards" HeaderSetCookie = "Set-Cookie" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderOrigin = "Origin" HeaderTimingAllowOrigin = "Timing-Allow-Origin" HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" HeaderDNT = "DNT" HeaderTk = "Tk" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentLocation = "Content-Location" HeaderContentType = "Content-Type" HeaderForwarded = "Forwarded" HeaderVia = "Via" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderLocation = "Location" HeaderFrom = "From" HeaderHost = "Host" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderUserAgent = "User-Agent" HeaderAllow = "Allow" HeaderServer = "Server" HeaderAcceptRanges = "Accept-Ranges" HeaderContentRange = "Content-Range" HeaderIfRange = "If-Range" HeaderRange = "Range" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderCrossOriginResourcePolicy = "Cross-Origin-Resource-Policy" HeaderExpectCT = "Expect-CT" HeaderFeaturePolicy = "Feature-Policy" HeaderPermissionsPolicy = "Permissions-Policy" HeaderPublicKeyPins = "Public-Key-Pins" HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXDownloadOptions = "X-Download-Options" HeaderXFrameOptions = "X-Frame-Options" HeaderXPoweredBy = "X-Powered-By" HeaderXXSSProtection = "X-XSS-Protection" HeaderLastEventID = "Last-Event-ID" HeaderNEL = "NEL" HeaderPingFrom = "Ping-From" HeaderPingTo = "Ping-To" HeaderReportTo = "Report-To" HeaderTE = "TE" HeaderTrailer = "Trailer" HeaderTransferEncoding = "Transfer-Encoding" HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" HeaderSecWebSocketKey = "Sec-WebSocket-Key" HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" HeaderSecWebSocketVersion = "Sec-WebSocket-Version" HeaderAcceptPatch = "Accept-Patch" HeaderAcceptPushPolicy = "Accept-Push-Policy" HeaderAcceptSignature = "Accept-Signature" HeaderAltSvc = "Alt-Svc" HeaderDate = "Date" HeaderIndex = "Index" HeaderLargeAllocation = "Large-Allocation" HeaderLink = "Link" HeaderPushPolicy = "Push-Policy" HeaderRetryAfter = "Retry-After" HeaderServerTiming = "Server-Timing" HeaderSignature = "Signature" HeaderSignedHeaders = "Signed-Headers" HeaderSourceMap = "SourceMap" HeaderUpgrade = "Upgrade" HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" HeaderXPingback = "X-Pingback" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderXRobotsTag = "X-Robots-Tag" HeaderXUACompatible = "X-UA-Compatible" HeaderTrace = "X-Trace" HeaderToken = "X-Token" HeaderTime = "X-Time" )
const ( MIMETextXML = "text/xml" MIMETextHTML = "text/html" MIMETextPlain = "text/plain" MIMETextJavaScript = "text/javascript" MIMEApplicationXML = "application/xml" MIMEApplicationJSON = "application/json" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationJavaScript = "application/javascript" MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEOctetStream = "application/octet-stream" MIMEMultipartForm = "multipart/form-data" MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8" MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" MIMEApplicationProtobufCharsetUTF8 = "application/protobuf; charset=utf-8" MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8" )
Variables ¶
var DefaultRecoverConfig = RecoverConfig{ EnableStackTrace: true, StackTraceHandler: func(ctx *Ctx, err interface{}, stack []byte) { log.Errorf("[Panic Recovered] %v\nStack Trace:\n%s", err, string(stack)) }, ErrorHandler: nil, }
DefaultRecoverConfig is the default Recover middleware config
var DiscoveryClient = func(c *core.ServiceDiscoveryClient) (Client, *fasthttp.Request) { panic("you should registe with discovery github.com/lazygophers/lrpc/middleware/service_discovery") }
var EmptyListenHandler = func(a *App, c *listenConfig) {}
var ErrRouteNotFound = fmt.Errorf("route not found")
ErrRouteNotFound indicates that no route was found for the given path
Functions ¶
Types ¶
type App ¶
type App struct {
// contains filtered or unexported fields
}
func (*App) AcquireCtx ¶
func (p *App) AcquireCtx(ctx *fasthttp.RequestCtx) *Ctx
func (*App) AddRoute ¶
func (p *App) AddRoute(r *Route, opts ...RouteOption)
func (*App) AddRoutes ¶
func (p *App) AddRoutes(rs []*Route, opts ...RouteOption)
func (*App) Connect ¶
func (p *App) Connect(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) DELETE ¶
func (app *App) DELETE(path string, handlers ...HandlerFunc) error
DELETE registers a DELETE route
func (*App) Delete ¶
func (p *App) Delete(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) ErrorHandler ¶
func (p *App) ErrorHandler(c *fasthttp.RequestCtx, err error)
func (*App) GET ¶
func (app *App) GET(path string, handlers ...HandlerFunc) error
GET registers a GET route
func (*App) Get ¶
func (p *App) Get(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) Group ¶
func (app *App) Group(prefix string, handlers ...HandlerFunc) *Group
Group creates a route group with prefix
func (*App) HEAD ¶
func (app *App) HEAD(path string, handlers ...HandlerFunc) error
HEAD registers a HEAD route
func (*App) Handle ¶
func (p *App) Handle(method, path string, handler HandlerFunc, opts ...RouteOption)
func (*App) Handler ¶
func (p *App) Handler(c *fasthttp.RequestCtx)
Handler is the main request handler that sets up tracing and calls ServeHTTP
func (*App) Head ¶
func (p *App) Head(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) ListenAndServe ¶
func (p *App) ListenAndServe(port int, handlers ...ListenHandler) (err error)
func (*App) OPTIONS ¶
func (app *App) OPTIONS(path string, handlers ...HandlerFunc) error
OPTIONS registers an OPTIONS route
func (*App) OnListen ¶
func (p *App) OnListen(logic func(ListenData) error)
func (*App) OnShutdown ¶
func (p *App) OnShutdown(logic func(ListenData))
func (*App) Options ¶
func (p *App) Options(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) PATCH ¶
func (app *App) PATCH(path string, handlers ...HandlerFunc) error
PATCH registers a PATCH route
func (*App) POST ¶
func (app *App) POST(path string, handlers ...HandlerFunc) error
POST registers a POST route
func (*App) PUT ¶
func (app *App) PUT(path string, handlers ...HandlerFunc) error
PUT registers a PUT route
func (*App) Patch ¶
func (p *App) Patch(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) Post ¶
func (p *App) Post(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) Put ¶
func (p *App) Put(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) ReleaseCtx ¶
func (*App) ServeHTTP ¶
func (app *App) ServeHTTP(ctx *fasthttp.RequestCtx)
ServeHTTP handles HTTP requests using the routing system
func (*App) ToHandlerFunc ¶
func (p *App) ToHandlerFunc(logic any) HandlerFunc
func (*App) Trace ¶
func (p *App) Trace(path string, handler HandlerFunc, opts ...RouteOption)
func (*App) Use ¶
func (app *App) Use(handlers ...HandlerFunc)
Use adds global middleware to all routers
type BaseResponse ¶
type BaseResponse struct {
Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"`
Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
Data any `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"`
Hint string `protobuf:"bytes,4,opt,name=hint,proto3" json:"hint,omitempty"`
}
type Config ¶
type Config struct {
Name string
OnError func(ctx *Ctx, err error)
// 用于统一的封包、权限等处理
AfterHandlerFuncWithRef func(ctx *Ctx, data reflect.Value, err error)
AfterHandlerFunc func(ctx *Ctx, err error)
// MaxRequestBodySize sets the maximum request body size (0 = unlimited)
MaxRequestBodySize int
// EnableCompression enables automatic response compression
EnableCompression bool
// CompressionLevel sets the compression level
CompressionLevel int
// CompressionMinLength sets minimum response size to compress
CompressionMinLength int
// ServerPoolConfig configures the server connection pool
ServerPoolConfig *pool.ServerPoolConfig
}
type Ctx ¶
type Ctx struct {
// contains filtered or unexported fields
}
func NewCtxTools ¶
func NewCtxTools() *Ctx
func (*Ctx) AllQueries ¶
AllQueries returns all query parameters
func (*Ctx) BodyParser ¶
func (*Ctx) ClearCookie ¶
ClearCookie clears a cookie
func (*Ctx) Context ¶
func (p *Ctx) Context() *fasthttp.RequestCtx
func (*Ctx) FormFile ¶
func (p *Ctx) FormFile(key string) (*multipart.FileHeader, error)
FormFile gets a file from multipart form
func (*Ctx) IsBodyStream ¶
func (*Ctx) MultipartForm ¶
MultipartForm gets the multipart form
func (*Ctx) SaveFile ¶
func (p *Ctx) SaveFile(fileHeader *multipart.FileHeader, path string) error
SaveFile saves an uploaded file to a path
func (*Ctx) SendStatus ¶
func (*Ctx) SendString ¶
func (*Ctx) SetTraceID ¶
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group represents a route group
func (*Group) DELETE ¶
func (g *Group) DELETE(path string, handlers ...HandlerFunc) error
DELETE registers a DELETE route in the group
func (*Group) GET ¶
func (g *Group) GET(path string, handlers ...HandlerFunc) error
GET registers a GET route in the group
func (*Group) Group ¶
func (g *Group) Group(prefix string, handlers ...HandlerFunc) *Group
Group creates a sub-group
func (*Group) HEAD ¶
func (g *Group) HEAD(path string, handlers ...HandlerFunc) error
HEAD registers a HEAD route in the group
func (*Group) OPTIONS ¶
func (g *Group) OPTIONS(path string, handlers ...HandlerFunc) error
OPTIONS registers an OPTIONS route in the group
func (*Group) PATCH ¶
func (g *Group) PATCH(path string, handlers ...HandlerFunc) error
PATCH registers a PATCH route in the group
func (*Group) POST ¶
func (g *Group) POST(path string, handlers ...HandlerFunc) error
POST registers a POST route in the group
func (*Group) PUT ¶
func (g *Group) PUT(path string, handlers ...HandlerFunc) error
PUT registers a PUT route in the group
func (*Group) Use ¶
func (g *Group) Use(handlers ...HandlerFunc) *Group
Use adds middleware to the group
type HandlerFunc ¶
func BodyLimit ¶
func BodyLimit(maxSize int) HandlerFunc
BodyLimit returns a middleware that limits request body size
func MergeHandler ¶
func MergeHandler(handlers ...HandlerFunc) HandlerFunc
func Recover ¶
func Recover(config ...RecoverConfig) HandlerFunc
Recover returns a middleware that recovers from panics
type Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
func (*Hooks) OnListen ¶
func (p *Hooks) OnListen(logic func(ListenData) error)
func (*Hooks) OnShutdown ¶
func (p *Hooks) OnShutdown(logic func(ListenData))
type ListenData ¶
type ListenHandler ¶
type ListenHandler func(a *App, c *listenConfig)
func ListenWithIp ¶
func ListenWithIp(ip string) ListenHandler
func ListenWithLan ¶
func ListenWithLan(prev6 ...bool) ListenHandler
func ListenWithLocal ¶
func ListenWithLocal(usev6 ...bool) ListenHandler
type MatchResult ¶
MatchResult contains the result of a route match
type ParamConstraint ¶
type ParamConstraint struct {
Type string // int, string, uuid, regex, digit, etc.
Min *int // min value for int, min length for string
Max *int // max value for int, max length for string
Len *int // fixed length for string
Regex *regexp.Regexp // regex pattern
Enum []string // enum values
}
ParamConstraint defines parameter validation rules
type RecoverConfig ¶
type RecoverConfig struct {
// EnableStackTrace enables printing stack trace
EnableStackTrace bool
// StackTraceHandler allows custom stack trace handling
StackTraceHandler func(ctx *Ctx, err interface{}, stack []byte)
// ErrorHandler allows custom error response
ErrorHandler func(ctx *Ctx, err interface{})
}
RecoverConfig defines the config for Recover middleware
type Route ¶
type Route struct {
Method string
Path string
Handler HandlerFunc
Before, After []HandlerFunc
// 可以存储一些类似于权限等信息,会在调用前写入到 local 中
Extra map[string]any
}
type RouteNode ¶
type RouteNode struct {
// contains filtered or unexported fields
}
RouteNode represents a node in the route tree
type RouteOption ¶
type RouteOption func(r *Route)
func RouteWithAfter ¶
func RouteWithAfter(after HandlerFunc) RouteOption
func RouteWithBefore ¶
func RouteWithBefore(before HandlerFunc) RouteOption
func RouteWithExtra ¶
func RouteWithExtra(extra map[string]any) RouteOption
func RouteWithMergeExtra ¶
func RouteWithMergeExtra(merge map[string]any) RouteOption
func RouteWithPrefix ¶
func RouteWithPrefix(prefix string) RouteOption
type RouteParam ¶
type RouteParam struct {
Name string
Constraint *ParamConstraint
}
RouteParam defines a route parameter
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router manages routes and middleware
type SearchResult ¶
type SearchTree ¶
type SearchTree[M any] struct { // contains filtered or unexported fields }
func NewSearchTree ¶
func NewSearchTree[M any]() *SearchTree[M]
func (*SearchTree[M]) Add ¶
func (p *SearchTree[M]) Add(route string, item M)
func (*SearchTree[M]) Search ¶
func (p *SearchTree[M]) Search(route string) (*SearchResult[M], bool)