slim

package module
v0.0.0-...-6fd8772 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2024 License: MIT Imports: 37 Imported by: 1

Documentation

Index

Constants

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = "application/json; charset=UTF-8"
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=UTF-8"
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = "application/xml; charset=UTF-8"
	MIMETextXML                          = "text/xml"
	MIMETextXMLCharsetUTF8               = "text/xml; charset=UTF-8"
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = "text/html; charset=UTF-8"
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = "text/plain; charset=UTF-8"
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	HeaderAccept         = "Accept"
	HeaderAcceptEncoding = "Accept-Encoding"
	// HeaderAllow is the name of the "Allow" header field used to list the set of methods
	// advertised as supported by the target resource. Returning an Allow header is mandatory
	// for status 405 (method not found) and useful for the OPTIONS method in responses.
	// See RFC 7231: https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Scheme"
	HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
	HeaderXRealIP             = "X-Real-IP"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "Origin"
	HeaderCacheControl        = "Cache-Control"
	HeaderConnection          = "Connection"

	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-Config"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-Config"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
)

Headers

View Source
const (
	Version = "0.0.1-dev"
)

Variables

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrTooManyRequests             = NewHTTPError(http.StatusTooManyRequests)
	ErrBadRequest                  = NewHTTPError(http.StatusBadRequest)
	ErrBadGateway                  = NewHTTPError(http.StatusBadGateway)
	ErrInternalServerError         = NewHTTPError(http.StatusInternalServerError)
	ErrRequestTimeout              = NewHTTPError(http.StatusRequestTimeout)
	ErrServiceUnavailable          = NewHTTPError(http.StatusServiceUnavailable)
	ErrValidatorNotRegistered      = errors.New("validator not registered")
	ErrRendererNotRegistered       = errors.New("renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
	ErrInvalidCertOrKeyType        = errors.New("invalid cert or key type, must be string or []byte")
	ErrInvalidListenerNetwork      = errors.New("invalid listener network")
	ErrFilesystemNotRegistered     = errors.New("filesystem not registered")
)

Errors

View Source
var DefaultRecoveryConfig = RecoveryConfig{
	StackSize:         4 << 10,
	DisableStackAll:   false,
	DisablePrintStack: false,
}

DefaultRecoveryConfig is the default Recovery middleware config.

Functions

func BindBody

func BindBody(c Context, i any) (err error)

BindBody binds request body contents to bindable object NB: then binding forms take note that this implementation uses standard library form parsing which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm

func BindPathParams

func BindPathParams(c Context, i any) error

BindPathParams binds path params to a bindable object

func BindQueryParams

func BindQueryParams(c Context, i any) error

BindQueryParams binds query params to bindable object

func ErrorHandler

func ErrorHandler(c Context, err error)

ErrorHandler 默认错误处理函数

func Explicitly

func Explicitly(c Context, next HandlerFunc) error

Explicitly 一个承上启下的中间件

func MethodNotAllowedHandler

func MethodNotAllowedHandler(_ Context) error

func NotFoundHandler

func NotFoundHandler(_ Context) error

Types

type Accept

type Accept struct {
	Type       string
	Subtype    string
	Quality    float64
	Extensions map[string]any
}

Accept represents a parsed `Accept(-Charset|-Encoding|-Language)` header.

type AcceptSlice

type AcceptSlice []Accept

AcceptSlice is a slice of accept.

func (AcceptSlice) Accepts

func (slice AcceptSlice) Accepts(ctype string) bool

Accepts returns true if the provided type is accepted.

func (AcceptSlice) Len

func (slice AcceptSlice) Len() int

Len implements the Len() method of the Sort interface.

func (AcceptSlice) Less

func (slice AcceptSlice) Less(i, j int) bool

Less implements the Less() method of the Sort interface. Elements are sorted in order of decreasing preference.

func (AcceptSlice) Negotiate

func (slice AcceptSlice) Negotiate(ctypes ...string) (string, int, error)

Negotiate returns a type that is accepted by both the AcceptSlice, and the list of types provided. If no common types are found, an empty string is returned.

func (AcceptSlice) Swap

func (slice AcceptSlice) Swap(i, j int)

Swap implements the Swap() method of the Sort interface.

type BindUnmarshaler

type BindUnmarshaler interface {
	// UnmarshalParam decodes and assigns a value from an form or query param.
	UnmarshalParam(param string) error
}

BindUnmarshaler is the interface used to wrap the UnmarshalParam method. Types that don't implement this, but do implement encoding.TextUnmarshaler will use that interface instead.

type Binder

type Binder interface {
	Bind(c Context, i any) error
}

Binder is the interface that wraps the Bind method.

type BytesGetter

type BytesGetter interface {
	Bytes() []byte
}

type Context

type Context interface {
	Context() stdctx.Context
	// Request returns `*http.Request`.
	// 返回当前请求的 `*http.Request` 结构体实例。
	Request() *http.Request
	// SetRequest sets `*http.Request`.
	// 设置 `*http.Request` 结构体实例。
	SetRequest(r *http.Request)
	// Response returns `slim.ResponseWriter`.
	Response() ResponseWriter
	// SetResponse sets `slim.ResponseWriter`.
	SetResponse(r ResponseWriter)
	// Logger returns the `Logger` instance.
	Logger() log.Logger
	// SetLogger Set the logger
	SetLogger(logger log.Logger)
	// Filesystem returns `fs.FS`.
	Filesystem() fs.FS
	// SetFilesystem sets `fs.FS`
	SetFilesystem(fs.FS)
	// IsTLS returns true if HTTP connection is TLS otherwise false.
	IsTLS() bool
	// IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
	IsWebSocket() bool
	// Scheme returns the HTTP protocol scheme, `http` or `https`.
	Scheme() string
	// RealIP returns the client's network address based on `X-Forwarded-For`
	// or `X-Real-IP` request header.
	// The behavior can be configured using `Slim#IPExtractor`.
	RealIP() string
	RequestURI() string
	// Accepts 返回支持的权重最高的媒体类型,若匹配失败则会返回空字符串。
	// 给出的值可以是标准的媒体类型(如 application/json),也可以是扩展名(如 json、xml 等)。
	Accepts(expect ...string) string
	// AcceptsEncodings 返回支持的权重最高的编码方式,若匹配失败则会返回空字符串。
	AcceptsEncodings(encodings ...string) string
	// AcceptsCharsets 返回支持的权重最高的字符集,若匹配失败则会返回空字符串。
	AcceptsCharsets(charsets ...string) string
	// AcceptsLanguages 返回支持的权重最高的语言,若匹配失败则会返回空字符串。
	AcceptsLanguages(languages ...string) string
	// AllowsMethods 返回允许的请求方法
	AllowsMethods() []string
	// RouteMatchType returns router match type for current context. This helps middlewares to distinguish which type
	// of match router found and how this request context handler chain could end:
	// * route match - this path + method had matching route.
	// * not found - this path did not match any routes enough to be considered match
	// * method not allowed - path had routes registered but for other method types then current request is
	// * unknown - initial state for fresh context before router tries to do routing
	//
	// Note: for pre-middleware (Mux.Use) this method result is always RouteMatchUnknown as at point router has not tried
	// to match request to route.
	RouteMatchType() RouteMatchType
	// RouteInfo returns current request route information. Method, Path, Name and params if they exist for matched route.
	// In the case of 404 (route not found) and 405 (method not allowed) RouteInfo returns generic struct for these cases.
	RouteInfo() RouteInfo
	// PathParam returns path parameter by name.
	PathParam(name string) string
	// PathParams returns path parameter values.
	PathParams() PathParams
	// SetPathParams set path parameter for during current request lifecycle.
	SetPathParams(params PathParams)
	// QueryParam returns the query param for the provided name.
	QueryParam(name string) string
	// QueryParams returns the query parameters as `url.Values`.
	QueryParams() url.Values
	// QueryString returns the URL query string.
	QueryString() string
	// FormValue returns the form field value for the provided name.
	FormValue(name string) string
	// FormParams returns the form parameters as `url.Values`.
	FormParams() (url.Values, error)
	// FormFile returns the multipart form file for the provided name.
	FormFile(name string) (*multipart.FileHeader, error)
	Header(key string) string
	SetHeader(key string, values ...string)
	// MultipartForm returns the multipart form.
	MultipartForm() (*multipart.Form, error)
	// Cookie returns the named cookie provided in the request.
	Cookie(name string) (*http.Cookie, error)
	// SetCookie adds a `Set-Cookie` header in HTTP response.
	SetCookie(cookie *http.Cookie)
	// Cookies return the HTTP cookies sent with the request.
	Cookies() []*http.Cookie
	// Get retrieves data from the context.
	Get(key string) any
	// Set saves data in the context.
	Set(key string, val any)
	// Bind binds the request body into a provided type `i`. The default binder
	// does it based on Content-Type header.
	Bind(i any) error
	// Validate validates provided `i`. It is usually called after `Context#Bind()`.
	// Validator must be registered using `Slim#Validator`.
	Validate(i any) error
	// Written returns whether the context response has been written to
	Written() bool
	// Render renders a template with data and sends a text/html response with status
	// code. Renderer must be registered using `Slim.Renderer`.
	Render(code int, name string, data any) error
	// HTML sends an HTTP response with status code.
	HTML(code int, html string) error
	// HTMLBlob sends an HTTP blob response with status code.
	HTMLBlob(code int, b []byte) error
	// String sends a string response with status code.
	String(code int, s string) error
	// JSON sends a JSON response with status code.
	JSON(code int, i any) error
	// JSONPretty sends a pretty-print JSON with status code.
	JSONPretty(code int, i any, indent string) error
	// JSONBlob sends a JSON blob response with status code.
	JSONBlob(code int, b []byte) error
	// JSONP sends a JSONP response with status code. It uses `callback` to construct
	// the JSONP payload.
	JSONP(code int, callback string, i any) error
	// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
	// to construct the JSONP payload.
	JSONPBlob(code int, callback string, b []byte) error
	// XML sends an XML response with status code.
	XML(code int, i any) error
	// XMLPretty sends a pretty-print XML with status code.
	XMLPretty(code int, i any, indent string) error
	// XMLBlob sends an XML blob response with status code.
	XMLBlob(code int, b []byte) error
	// Blob sends a blob response with a status code and content type.
	Blob(code int, contentType string, b []byte) error
	// Stream sends a streaming response with status code and content type.
	Stream(code int, contentType string, r io.Reader) error
	// File sends a response with the content of the file.
	File(file string, filesystem ...fs.FS) error
	// Attachment sends a response as attachment, prompting client to save the
	// file.
	Attachment(file string, name string) error
	// Inline sends a response as inline, opening the file in the browser.
	Inline(file string, name string) error
	// NoContent sends a response with nobody and a status code.
	NoContent(code ...int) error
	// Redirect redirects the request to a provided URL with status code.
	Redirect(code int, url string) error
	// Error invokes the registered HTTP error handler.
	// NB: Avoid using this method. It is better to return errors, so middlewares up in a chain could act on returned error.
	Error(err error)
	// Slim 返回 Slim 实例
	Slim() *Slim
}

Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.

type DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

func (b *DefaultBinder) Bind(c Context, i any) (err error)

Bind implements the `Binder#Bind` function. Binding is done in the following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous step bound values. For single source binding use their own methods BindBody, BindQueryParams, BindPathParams.

func (*DefaultBinder) BindHeaders

func (b *DefaultBinder) BindHeaders(c Context, i any) error

BindHeaders binds HTTP headers to a bindable object

type EditableContext

type EditableContext interface {
	Context
	// RawPathParams returns raw path pathParams value.
	RawPathParams() *PathParams
	// SetRawPathParams replaces any existing param values with new values for this context lifetime (request).
	SetRawPathParams(params *PathParams)
	// SetRouteMatchType sets the RouteMatchType of router match for this request.
	SetRouteMatchType(t RouteMatchType)
	SetAllowsMethods(methods []string)
	// SetRouteInfo sets the route info of this request to the context.
	SetRouteInfo(ri RouteInfo)
	// Reset resets the context after request completes. It must be called along
	// with `Slim#AcquireContext()` and `Slim#ReleaseContext()`.
	// See `Slim#ServeHTTP()`
	Reset(w http.ResponseWriter, r *http.Request)
}

type ErrorHandlerFunc

type ErrorHandlerFunc func(c Context, err error)

ErrorHandlerFunc 错误处理函数签名

type HTTPError

type HTTPError struct {
	StatusCode int   `json:"-"`
	Message    any   `json:"message"`
	Internal   error `json:"-"` // Stores the error returned by an external dependency
}

HTTPError represents an error that occurred while handling a request.

func NewHTTPError

func NewHTTPError(code int, message ...any) *HTTPError

NewHTTPError creates a new HTTPError instance.

func NewHTTPErrorWithInternal

func NewHTTPErrorWithInternal(code int, internalError error, message ...any) *HTTPError

NewHTTPErrorWithInternal creates a new HTTPError instance with an internal error set.

func (*HTTPError) Error

func (he *HTTPError) Error() string

Error makes it compatible with `error` interface.

func (*HTTPError) Unwrap

func (he *HTTPError) Unwrap() error

Unwrap satisfies the Go 1.13 error wrapper interface.

func (*HTTPError) WithInternal

func (he *HTTPError) WithInternal(err error) *HTTPError

WithInternal returns clone of HTTPError with err set to HTTPError.Internal field

type HandlerFunc

type HandlerFunc func(c Context) error

HandlerFunc HTTP请求处理函数签名

func ComposeChainHandler

func ComposeChainHandler(route Route) HandlerFunc

ComposeChainHandler 组合路由收集器的中间件和路由的中间件

func StaticDirectoryHandler

func StaticDirectoryHandler(root string, disablePathUnescaping bool) HandlerFunc

StaticDirectoryHandler creates handler function to serve files from given a root path

func Tap

func WrapHandler

func WrapHandler(h http.Handler) HandlerFunc

WrapHandler wraps `http.Handler` into `slim.HandlerFunc`.

type JSONSerializer

type JSONSerializer struct{}

JSONSerializer 为 JSON 实现序列化接口

func (*JSONSerializer) Deserialize

func (*JSONSerializer) Deserialize(r io.Reader, v any) error

Deserialize 反序列化数据并绑定到 v 上

func (*JSONSerializer) Serialize

func (*JSONSerializer) Serialize(w io.Writer, v any, indent string) error

Serialize 序列化数据到 w 接口

type LoggingConfig

type LoggingConfig struct {
	// DisableRequestID 是否开启 RequestID
	DisableRequestID bool
	// RequestIDGenerator 请求 ID 生成器
	RequestIDGenerator func(c Context) string
	// ForkedPrefixes 自定义的关联前缀的日志实例到请求上下文中,比如:
	//
	//   LoggingConfig{
	//     DisableRequestID: map[string]string{
	//       "db:logger":    "db",    // 将数据库操作与请求关联
	//       "redis:logger": "redis", // 将 redis 操作与请求关联
	//       //...其它关联
	//     }
	//   }
	ForkedPrefixes map[string]string
}

func (LoggingConfig) ToMiddleware

func (config LoggingConfig) ToMiddleware() MiddlewareFunc

type Map

type Map map[string]any

Map defines a generic map of type `map[string]any`.

type MiddlewareComposer

type MiddlewareComposer interface {
	// Compose 将注册的所有中间件合并成一个中间件
	Compose() MiddlewareFunc
}

MiddlewareComposer 中间件合成器接口

type MiddlewareConfigurator

type MiddlewareConfigurator interface {
	// ToMiddleware 将实例转换成中间件函数
	ToMiddleware() MiddlewareFunc
}

type MiddlewareFunc

type MiddlewareFunc func(c Context, next HandlerFunc) error

MiddlewareFunc 请求中间件

func Compose

func Compose(middleware ...MiddlewareFunc) MiddlewareFunc

Compose 合并多个中间件为一个,实现洋葱模型, 有别于 gin/chi/echo 等框架的的后入先出模式。

func Logging

func Logging() MiddlewareFunc

func LoggingWithConfig

func LoggingWithConfig(config LoggingConfig) MiddlewareFunc

func Recovery

func Recovery() MiddlewareFunc

Recovery returns a middleware which recovers from panics anywhere in the chain and handles the control to the centralized ErrorHandler.

func RecoveryWithConfig

func RecoveryWithConfig(config RecoveryConfig) MiddlewareFunc

RecoveryWithConfig returns Recovery middleware with config or panics on invalid configuration.

func Static

func Static(root string) MiddlewareFunc

Static returns Static middleware to serve static content from the provided root directory.

func WrapMiddleware

func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc

WrapMiddleware wraps `func(http.Handler) http.Handler` into `slim.MiddlewareFunc`

type MiddlewareRegistrar

type MiddlewareRegistrar interface {
	// Use 注册中间件
	Use(middleware ...MiddlewareFunc)
	// Middleware 返回注册的所有中间件
	Middleware() []MiddlewareFunc
}

MiddlewareRegistrar 中间件注册接口

type Negotiator

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

Negotiator An HTTP content negotiator

func NewNegotiator

func NewNegotiator(capacity int, onParse func(accept *Accept)) *Negotiator

func (*Negotiator) Accepts

func (n *Negotiator) Accepts(header string, ctypes ...string) string

func (*Negotiator) Charset

func (n *Negotiator) Charset(r *http.Request, charsets ...string) string

func (*Negotiator) Encoding

func (n *Negotiator) Encoding(r *http.Request, encodings ...string) string

func (*Negotiator) Language

func (n *Negotiator) Language(r *http.Request, languages ...string) string

func (*Negotiator) Slice

func (n *Negotiator) Slice(header string) AcceptSlice

func (*Negotiator) Type

func (n *Negotiator) Type(r *http.Request, types ...string) string

type PathParam

type PathParam struct {
	Name  string
	Value string
}

type PathParams

type PathParams []PathParam

PathParams 路由参数

func (PathParams) Get

func (p PathParams) Get(name string, defaultValue ...string) string

func (PathParams) Lookup

func (p PathParams) Lookup(name string) (string, bool)

type RecoveryConfig

type RecoveryConfig struct {
	// Size of the stack to be printed.
	// Optional. Default value 4KB.
	StackSize int
	// DisableStackAll disables formatting stack traces of all other goroutines
	// into buffer after the trace for the current goroutine.
	// Optional. Default value is false.
	DisableStackAll bool
	// DisablePrintStack disables printing stack trace.
	// Optional. Default value as false.
	DisablePrintStack bool
}

RecoveryConfig defines the config for Recovery middleware.

func (RecoveryConfig) ToMiddleware

func (config RecoveryConfig) ToMiddleware() MiddlewareFunc

ToMiddleware converts RecoveryConfig to middleware or returns an error for invalid configuration

type Renderer

type Renderer interface {
	Render(c Context, w io.Writer, name string, data any) error
}

Renderer is the interface that wraps the Render function.

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	http.Pusher
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Written returns whether the ResponseWriter has been written.
	Written() bool
	// Size returns the size of the response body.
	Size() int
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a ResponseWriter if the functionality calls for it.

func NewResponseWriter

func NewResponseWriter(method string, rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an `http.ResponseWriter`

type Route

type Route interface {
	// Router 返回所属路由器
	Router() Router
	// Collector 返回所属收集器
	Collector() RouteCollector
	// Name 返回路由名称
	Name() string
	// SetName 设置路由名称,返回 Route 方便链式操作。
	SetName(name string) Route
	// Pattern 路由路径表达式
	Pattern() string
	// Methods 返回支持的 HTTP 请求方法
	Methods() []string
	// Handler 返回注册的请求处理器函数
	Handler() HandlerFunc
	// Params 返回支持的路由参数列表
	Params() []string
	// ToRouteInfo 返回路由描述接口实例
	ToRouteInfo() RouteInfo
	// Use 注册中间件,返回 Route 方便链式操作。
	Use(middleware ...MiddlewareFunc) Route
	// Middleware 返回注册的中间件
	Middleware() []MiddlewareFunc
	MiddlewareComposer
}

Route 路由接口

type RouteCollector

type RouteCollector interface {
	// Prefix 返回路由共用前缀
	Prefix() string
	// Parent 返回上级路由收集器
	Parent() RouteCollector
	// Router 返回所属路由器
	Router() Router
	MiddlewareRegistrar
	MiddlewareComposer
	RouteRegistrar
}

RouteCollector 路由收集器接口

func NewRouteCollector

func NewRouteCollector(prefix string, parent RouteCollector, router Router) RouteCollector

type RouteInfo

type RouteInfo interface {
	// Router 返回所属路由器
	Router() Router
	// Collector 返回所属收集器
	Collector() RouteCollector
	// Name 返回路由名称
	Name() string
	// Methods 返回支持的请求方法列表
	Methods() []string
	// Pattern 路由路径表达式
	Pattern() string
	// Params 返回支持的路由参数列表
	Params() []string
	// Reverse 通过提供的参数来反转路由表达式,返回为真实请求路径。
	// 如果参数为空或 nil 时则尝试使用用默认值,若无法解决参数
	// 则会 panic 错误
	Reverse(params ...any) string
}

RouteInfo 路由描述接口

type RouteMatch

type RouteMatch struct {
	// Type contains a result as enumeration of Router.Match and helps to understand did Router actually matched Route or
	// what kind of error case (404/405) we have at the end of the handler chain.
	Type RouteMatchType
	// AllowMethods 能够接受处理的请求方法列表,主要
	// 在 Type 值为 RouteMatchMethodNotAllowed 时被使用。
	AllowMethods []string
	// Handler is function(chain) that was matched by router. In case of no match could result to ErrNotFound or ErrMethodNotAllowed.
	Handler HandlerFunc
	// RouteInfo is information about the route we just matched
	RouteInfo RouteInfo
}

RouteMatch is result object for Router.Match. Its main purpose is to avoid allocating memory for PathParams inside router.

type RouteMatchType

type RouteMatchType uint8

RouteMatchType describes possible states that request could be in perspective of routing

const (
	// RouteMatchUnknown is state before routing is done. Default state for fresh context.
	RouteMatchUnknown RouteMatchType = iota
	// RouteMatchNotFound is state when router did not find matching route for current request
	RouteMatchNotFound
	// RouteMatchMethodNotAllowed is state when router did not find route with matching path + method for current request.
	// Although router had a matching route with that path but different method.
	RouteMatchMethodNotAllowed
	// RouteMatchFound is state when router found exact match for path + method combination
	RouteMatchFound
)

type RouteRegistrar

type RouteRegistrar interface {
	// Group 实现路由分组注册,实际调用 `RouteCollector.Route` 实现
	Group(fn func(sub RouteCollector))
	// Route 以指定前缀实现路由分组注册
	Route(prefix string, fn func(sub RouteCollector))
	// Some registers a new route for multiple HTTP methods and path with matching
	// handler in the router. Panics on error.
	Some(methods []string, pattern string, h HandlerFunc) Route
	// Any registers a new route for all supported HTTP methods and path with matching
	// handler in the router. Panics on error.
	Any(pattern string, h HandlerFunc) Route
	// CONNECT registers a new CONNECT route for a path with matching handler in
	// the router. Panics on error.
	CONNECT(pattern string, h HandlerFunc) Route
	// DELETE registers a new DELETE route for a path with matching handler in
	// the router. Panics on error.
	DELETE(pattern string, h HandlerFunc) Route
	// GET registers a new GET route for a path with matching handler in
	// the router. Panics on error.
	GET(pattern string, h HandlerFunc) Route
	// HEAD registers a new HEAD route for a path with matching handler in
	// the router. Panics on error.
	HEAD(pattern string, h HandlerFunc) Route
	// OPTIONS registers a new OPTIONS route for a path with matching handler
	// in the router. Panics on error.
	OPTIONS(pattern string, h HandlerFunc) Route
	// PATCH registers a new PATCH route for a path with matching handler in
	// the router. Panics on error.
	PATCH(pattern string, h HandlerFunc) Route
	// POST registers a new POST route for a path with matching handler in
	// the router. Panics on error.
	POST(pattern string, h HandlerFunc) Route
	// PUT registers a new PUT route for a path with matching handler in
	// the router. Panics on error.
	PUT(pattern string, h HandlerFunc) Route
	// TRACE registers a new TRACE route for a path with matching handler in
	// the router. Panics on error.
	TRACE(pattern string, h HandlerFunc) Route
	// Static registers a new route with path prefix to serve static files
	// from the provided root directory. Panics on error.
	Static(prefix, root string) Route
	// File registers a new route with a path to serve a static file.
	// Panics on error.
	File(pattern, file string) Route
}

type Router

type Router interface {
	// Add 注册请求处理器,返回对应的路由接口实例
	Add([]string, string, HandlerFunc) (Route, error)
	// Remove 移除路由
	Remove(methods []string, path string) error
	// Routes 返回注册的路由
	Routes() []Route
	// Match 匹配路由
	Match(req *http.Request, params *PathParams) RouteMatch
	MiddlewareRegistrar
	MiddlewareComposer
	RouteRegistrar
}

Router is interface for routing requests to registered routes.

func NewRouter

func NewRouter(config RouterConfig) Router

type RouterConfig

type RouterConfig struct {
	AllowOverwritingRoute    bool
	UnescapePathParamValues  bool
	UseEscapedPathForRouting bool
	RoutingTrailingSlash     bool
	RouteCollector           RouteCollector
	ErrorHandler             ErrorHandlerFunc
}

type Serializer

type Serializer interface {
	Serialize(w io.Writer, v any, indent string) error
	Deserialize(r io.Reader, v any) error
}

Serializer 序列化 json 或 xml

type Slim

type Slim struct {
	NewContextFunc       func(pathParamAllocSize int) EditableContext // 自定义 `slim.Context` 构造函数
	ErrorHandler         ErrorHandlerFunc
	Filesystem           fs.FS // 静态资源文件系统,默认值 `os.DirFS(".")`。
	Binder               Binder
	Validator            Validator
	Renderer             Renderer // 自定义错误处理函数
	JSONSerializer       Serializer
	XMLSerializer        Serializer
	Logger               log.Logger
	Server               *http.Server
	TLSServer            *http.Server
	Listener             net.Listener
	TLSListener          net.Listener
	StdLogger            *stdLog.Logger
	AutoTLSManager       autocert.Manager
	DisableHTTP2         bool
	HideBanner           bool
	HidePort             bool
	ListenerNetwork      string
	Debug                bool     // 是否开启调试模式
	MultipartMemoryLimit int64    // 文件上传大小限制
	PrettyIndent         string   // json/xml 格式化缩进
	JSONPCallbacks       []string // jsonp 回调函数
	// contains filtered or unexported fields
}

func Classic

func Classic() *Slim

func New

func New() *Slim

func (*Slim) AcquireContext

func (s *Slim) AcquireContext() Context

AcquireContext returns 自上下文缓存池中返回一个空闲的 `mux.Context` 实例。 在不需要的时候,必须通过调用 `Mux.ReleaseContext` 方法归还该上下文。

func (*Slim) Any

func (s *Slim) Any(pattern string, h HandlerFunc) Route

Any registers a new route for all supported HTTP methods and path with matching handler in the router. Panics on error.

func (*Slim) CONNECT

func (s *Slim) CONNECT(path string, h HandlerFunc) Route

CONNECT registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) Close

func (s *Slim) Close() error

Close immediately stops the server. It internally calls `http.Server#Close()`.

func (*Slim) DELETE

func (s *Slim) DELETE(path string, h HandlerFunc) Route

DELETE registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) File

func (s *Slim) File(path, file string) Route

File registers a new route with a path to serve a static file. Panics on error.

func (*Slim) GET

func (s *Slim) GET(path string, h HandlerFunc) Route

GET registers a new GET route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) Group

func (s *Slim) Group(fn func(sub RouteCollector))

Group 实现路由分组注册,实际调用 `RouteCollector.Route` 实现

func (*Slim) HEAD

func (s *Slim) HEAD(path string, h HandlerFunc) Route

HEAD registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) Host

func (s *Slim) Host(name string, middleware ...MiddlewareFunc) Router

Host 通过提供名称和中间件函数创建对应 `host` 的路由器实例

func (*Slim) ListenerAddr

func (s *Slim) ListenerAddr() net.Addr

ListenerAddr returns net.Addr for Listener

func (*Slim) Negotiator

func (s *Slim) Negotiator() *Negotiator

Negotiator 返回内容协商工具

func (*Slim) NewContext

func (s *Slim) NewContext(w http.ResponseWriter, r *http.Request) Context

func (*Slim) NewRouter

func (s *Slim) NewRouter() Router

func (*Slim) OPTIONS

func (s *Slim) OPTIONS(path string, h HandlerFunc) Route

OPTIONS registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) PATCH

func (s *Slim) PATCH(path string, h HandlerFunc) Route

PATCH registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) POST

func (s *Slim) POST(path string, h HandlerFunc) Route

POST registers a new POST route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) PUT

func (s *Slim) PUT(path string, h HandlerFunc) Route

PUT registers a new PUT route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) ReleaseContext

func (s *Slim) ReleaseContext(c Context)

ReleaseContext 归还通过 `Mux.AcquireContext` 获取的 `mux.Context` 实例 到上下文缓存池中.

func (*Slim) ResetRouterCreator

func (s *Slim) ResetRouterCreator(creator func(s *Slim) Router)

ResetRouterCreator 重置路由器创建函数。 注意:会立即重新创建默认路由器,并且 vhost 路由器会被清除。

func (*Slim) Route

func (s *Slim) Route(prefix string, fn func(sub RouteCollector))

Route 以指定前缀实现路由分组注册

func (*Slim) Router

func (s *Slim) Router() Router

Router 返回默认路由器

func (*Slim) RouterFor

func (s *Slim) RouterFor(host string) Router

RouterFor 返回与指定 `host` 相关的路由器

func (*Slim) Routers

func (s *Slim) Routers() map[string]Router

Routers 返回 vhost 的 `host => router` 映射

func (*Slim) ServeHTTP

func (s *Slim) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP 实现 `http.Handler` 接口

func (*Slim) SetNegotiator

func (s *Slim) SetNegotiator(negotiator *Negotiator)

SetNegotiator 设置自定义内容协商工具

func (*Slim) Shutdown

func (s *Slim) Shutdown(ctx stdctx.Context) error

Shutdown stops the server gracefully. It internally calls `http.Server#Shutdown()`.

func (*Slim) Some

func (s *Slim) Some(methods []string, pattern string, h HandlerFunc) Route

Some registers a new route for multiple HTTP methods and path with matching handler in the router. Panics on error.

func (*Slim) Start

func (s *Slim) Start(address string) error

Start starts an HTTP server.

func (*Slim) StartAutoTLS

func (s *Slim) StartAutoTLS(address string) error

StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.

func (*Slim) StartH2CServer

func (s *Slim) StartH2CServer(address string, h2s *http2.Server) error

StartH2CServer starts a custom http/2 server with h2c (HTTP/2 Cleartext).

func (*Slim) StartServer

func (s *Slim) StartServer(srv *http.Server) (err error)

StartServer starts a custom http server.

func (*Slim) StartTLS

func (s *Slim) StartTLS(address string, certFile, keyFile interface{}) (err error)

StartTLS starts an HTTPS server. If `certFile` or `keyFile` is `string`, the values are treated as file paths. If `certFile` or `keyFile` is `[]byte`, the values are treated as the certificate or key as-is.

func (*Slim) Static

func (s *Slim) Static(prefix, root string) Route

Static registers a new route with path prefix to serve static files from the provided root directory. Panics on error.

func (*Slim) TLSListenerAddr

func (s *Slim) TLSListenerAddr() net.Addr

TLSListenerAddr returns net.Addr for TLSListener

func (*Slim) TRACE

func (s *Slim) TRACE(path string, h HandlerFunc) Route

TRACE registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.

func (*Slim) Use

func (s *Slim) Use(middleware ...MiddlewareFunc)

Use 注册全局中间件

type StaticConfig

type StaticConfig struct {
	// Root directory from where the static content is served.
	// Required.
	Root string
	// Index file for serving a directory.
	// Optional. Default value "index.html".
	Index string
	// Enable HTML5 mode by forwarding all not-found requests to root so that
	// SPA (single-page application) can handle the routing.
	// Optional. Default value is false.
	HTML5 bool
	// Filesystem provides access to the static content.
	// Optional. Default to http.Dir(config.Root)
	Filesystem http.FileSystem
}

func (StaticConfig) ToMiddleware

func (config StaticConfig) ToMiddleware() MiddlewareFunc

type Validator

type Validator interface {
	Validate(i any) error
}

Validator is the interface that wraps the Validate function.

type XMLSerializer

type XMLSerializer struct{}

func (*XMLSerializer) Deserialize

func (*XMLSerializer) Deserialize(r io.Reader, v any) error

func (*XMLSerializer) Serialize

func (*XMLSerializer) Serialize(w io.Writer, v any, indent string) error

Jump to

Keyboard shortcuts

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