slim

package module
v0.0.0-...-64da609 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2025 License: MIT Imports: 29 Imported by: 1

Documentation

Index

Constants

View Source
const Version = "0.0.3"

Version 项目当前版本信息

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("slim: validator not registered")
	ErrRendererNotRegistered       = errors.New("slim: renderer not registered")
	ErrInvalidRedirectCode         = errors.New("slim: invalid redirect status code")
	ErrCookieNotFound              = errors.New("slim: cookie not found")
	ErrFilesystemNotRegistered     = errors.New("slim: filesystem not registered")
	ErrLoggerNotRegistered         = errors.New("slim: logger not registered")
)

Errors

View Source
var (
	SlimContextKey     = &contextKey{"slim"}
	RequestContextKey  = &contextKey{"request"}
	ResponseContextKey = &contextKey{"response"}
	ContextKey         = &contextKey{"context"}
)
View Source
var DefaultLoggerConfig = LoggerConfig{
	Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}",` +
		`"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` +
		`"status":${status},"error":"${error}","latency":${latency},"latency_human":"${latency_human}"` +
		`,"bytes_in":${bytes_in},"bytes_out":${bytes_out}}` + "\n",
	CustomTimeFormat: "2006-01-02 15:04:05.00000",
}

DefaultLoggerConfig is the default Logger middleware config.

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 DefaultErrorHandler

func DefaultErrorHandler(c Context, err error)

DefaultErrorHandler 默认错误处理函数

func ExecuteFunc

func ExecuteFunc(template, startTag, endTag string, w io.Writer, f TagFunc) (int64, error)

ExecuteFunc calls f on each template tag (placeholder) occurrence.

Returns the number of bytes written to w.

This function is optimized for constantly changing templates. Use Template.ExecuteFunc for frozen templates.

func Explicitly

func Explicitly(c Context, next HandlerFunc) error

Explicitly 一个承上启下的中间件

func MethodNotAllowedHandler

func MethodNotAllowedHandler(_ Context) error

func NotFoundHandler

func NotFoundHandler(_ Context) error

func SliceByteToString

func SliceByteToString(b []byte) string

func StringToSliceByte

func StringToSliceByte(s string) []byte

Types

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 实现 context.Context 接口
	context.Context
	// Request 返回当前请求的 `*http.Request` 结构体实例
	Request() *http.Request
	// SetRequest 为上下文设置新的 `*http.Request` 结构体实例。
	SetRequest(r *http.Request)
	// Response 返回当前请求的 `http.ResponseWriter` 接口实现
	Response() ResponseWriter
	// SetResponse 为上下文设置新的 `http.ResponseWriter` 实现
	SetResponse(r ResponseWriter)
	// Logger returns the `Logger` instance.
	Logger() Logger
	// SetLogger Set the logger
	SetLogger(logger Logger)
	// Filesystem returns `fs.FS`.
	Filesystem() fs.FS
	// SetFilesystem sets `fs.FS`
	SetFilesystem(fs.FS)
	// IsTLS 判断 HTTP 连接是否采用了 Transport Layer Security (TLS) 协议,
	// 如果是返回 true,否则返回 false。
	IsTLS() bool
	// IsWebSocket 判断 HTTP 连接是否为 WebSocket 协议,如果
	// 是就返回 true,否则返回 false。
	IsWebSocket() bool
	// Scheme 获取 HTTP 请求的协议方案,返回值为 `http` 或者 `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
	Is(types ...string) 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 slim-middleware (Slim.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 网络请求上下文,包含了请求数据(路径、路径参数、载荷) 和响应对象以及已注册的处理程序等。

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 ErrorHandler

type ErrorHandler interface {
	// HandleError 处理错误
	HandleError(c Context, err error)
}

ErrorHandler is a centralized error handler.

type ErrorHandlerFunc

type ErrorHandlerFunc func(c Context, err error)

ErrorHandlerFunc defines a function to centralize errors.

func (ErrorHandlerFunc) HandleError

func (h ErrorHandlerFunc) HandleError(c Context, err error)

HandleError 实现 ErrorHandler 接口

type ErrorHandlerRegistrar

type ErrorHandlerRegistrar interface {
	// UseErrorHandler 注册错误处理器
	// 重复调用该方法会覆盖之前设置的错误处理器
	UseErrorHandler(h ErrorHandler)
}

ErrorHandlerRegistrar 错误处理器注册接口

type HTTPError

type HTTPError struct {
	Code     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 defines a function to serve HTTP requests.

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`.

func WrapHandlerFunc

func WrapHandlerFunc(h http.HandlerFunc) HandlerFunc

WrapHandlerFunc wraps `http.HandlerFunc` into `slim.HandlerFunc`.

type IPExtractor

type IPExtractor func(*http.Request) string

IPExtractor is a function to extract IP addr from http.Request. Set appropriate one to Slim.IPExtractor.

type Logger

type Logger interface {
	Output() io.Writer
	SetOutput(w io.Writer)
	Prefix() string
	SetPrefix(p string)
	Flags() int
	SetFlags(flag int)
	Level() int
	SetLevel(v int)
	StacktraceLevel() int
	SetStacktraceLevel(v int)
	Print(i ...any)
	Printf(format string, args ...any)
	Printj(j map[string]any)
	Debug(i ...any)
	Debugf(format string, args ...any)
	Debugj(j map[string]any)
	Info(i ...any)
	Infof(format string, args ...any)
	Infoj(j map[string]any)
	Warn(i ...any)
	Warnf(format string, args ...any)
	Warnj(j map[string]any)
	Error(i ...any)
	Errorf(format string, args ...any)
	Errorj(j map[string]any)
	Panic(i ...any)
	Panicj(j map[string]any)
	Panicf(format string, args ...any)
	Fatal(i ...any)
	Fatalj(j map[string]any)
	Fatalf(format string, args ...any)
}

Logger defines the logging interface.

type LoggerConfig

type LoggerConfig struct {
	// Tags to construct the logger format.
	//
	// - time_unix
	// - time_unix_milli
	// - time_unix_micro
	// - time_unix_nano
	// - time_rfc3339
	// - time_rfc3339_nano
	// - time_custom
	// - id (Request ID)
	// - remote_ip
	// - uri
	// - host
	// - method
	// - path
	// - route
	// - protocol
	// - referer
	// - user_agent
	// - status
	// - error
	// - latency (In nanoseconds)
	// - latency_human (Human readable)
	// - bytes_in (Bytes received)
	// - bytes_out (Bytes sent)
	// - header:<NAME>
	// - query:<NAME>
	// - form:<NAME>
	// - custom (see CustomTagFunc field)
	//
	// Example "${remote_ip} ${status}"
	//
	// Optional. Default value DefaultLoggerConfig.Format.
	Format string `yaml:"format"`

	// Optional. Default value DefaultLoggerConfig.CustomTimeFormat.
	CustomTimeFormat string `yaml:"custom_time_format"`

	// CustomTagFunc is function called for `${custom}` tag to output user implemented text by writing it to buf.
	// Make sure that outputted text creates valid JSON string with other logged tags.
	// Optional.
	CustomTagFunc func(c Context, buf *bytes.Buffer) (int, error)

	// Output is a writer where logs in JSON format are written.
	// Optional. Default value os.Stdout.
	Output io.Writer
	// contains filtered or unexported fields
}

LoggerConfig defines the config for Logger middleware.

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 defines a function to process middleware.

func Compose

func Compose(middleware ...MiddlewareFunc) MiddlewareFunc

Compose 将多个中间件合并为一个,在执行期间,会自上而下传递请求, 之后过滤并逆序返回响应,因此实现了友好且符合直观思维的洋葱模型。

func Logging

func Logging() MiddlewareFunc

Logging returns a middleware that logs HTTP requests.

func LoggingWithConfig

func LoggingWithConfig(config LoggerConfig) MiddlewareFunc

LoggingWithConfig returns a Logger middleware with config. See: `Logging()`.

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 PathParam

type PathParam struct {
	Name  string // 参数名
	Value string // 参数值
}

PathParam 路径参数

type PathParams

type PathParams []PathParam

PathParams 路由参数列表

func (PathParams) Get

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

Get 获取与 name 对应的值,若不存在,则返回提供的默认值

func (PathParams) Lookup

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

Lookup 检查并返回参数值, 第一个返回值是与 name 对应的值,第二个返回值表示是否存在。

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 {
	// MiddlewareRegistrar 实现中间件注册接口
	MiddlewareRegistrar
	// MiddlewareComposer 实现中间件合成器接口
	MiddlewareComposer
	// Router 返回所属路由器
	Router() Router
	// Collector 返回所属收集器
	Collector() RouteCollector
	// Name 返回路由名称
	Name() string
	// SetName 设置路由名称
	SetName(name string)
	// Pattern 路由路径表达式
	Pattern() string
	// Methods 返回支持的 HTTP 请求方法
	Methods() []string
	// Handler 返回注册的请求处理器函数
	Handler() HandlerFunc
	// Params 返回支持的路由参数列表
	Params() []string
	// RouteInfo 返回路由描述接口实现
	RouteInfo() RouteInfo
}

Route 路由接口

type RouteCollector

type RouteCollector interface {
	// MiddlewareRegistrar 实现中间件注册接口
	MiddlewareRegistrar
	// MiddlewareComposer 实现中间件合成器接口
	MiddlewareComposer
	// ErrorHandlerRegistrar 实现错误处理器注册接口
	ErrorHandlerRegistrar
	// RouteRegistrar 实现路由注册器接口
	RouteRegistrar
	// Prefix 返回路由共用前缀
	Prefix() string
	// Parent 返回上级路由收集器
	Parent() RouteCollector
	// Router 返回所属路由器
	Router() Router
}

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
	// String 返回字符串形式
	String() 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 RouteMatcher

type RouteMatcher interface {
	// Match 匹配路由
	Match(r *http.Request, p *PathParams) RouteMatch
}

RouteMatcher 路由匹配器接口

type RouteRegistrar

type RouteRegistrar interface {
	// Group 对路由进行分组,方便我们把一个或多个中间件作用在
	// 同组路由上,并使它们在错误和 panic 上使用相同的处理方式
	Group(fn func(sub RouteCollector))
	// Route 为同组路由指定相同的前缀,使用方法和内部逻辑与
	// 方法 Group 保持一致
	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
	// Handle 注册一个支持指定请求方法的路由
	Handle(method, 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
}

RouteRegistrar 路由注册器接口

其中 RouteRegistrar.Some 和 RouteRegistrar.Any 以及 RouteRegistrar.Handle 为我们自定义非标准的 HTTP 请求方法 提供了扩展的能力。

type Router

type Router interface {
	// MiddlewareRegistrar 实现中间件注册接口
	MiddlewareRegistrar
	// MiddlewareComposer 实现中间件合成器接口
	MiddlewareComposer
	// ErrorHandlerRegistrar 实现错误处理器注册接口
	ErrorHandlerRegistrar
	// RouteRegistrar 实现路由注册器接口
	RouteRegistrar
	// RouteMatcher 实现路由匹配器接口
	RouteMatcher
	// Add registers a new route for method and path with matching handler.
	Add([]string, string, HandlerFunc) (Route, error)
	// Remove 移除路由
	Remove(methods []string, path string) error
	// Routes 返回注册的路由
	Routes() []Route
	// URI generates a URI from handler.
	URI(h HandlerFunc, params ...any) string
	// Reverse generates a URL from route name and provided parameters.
	Reverse(name string, params ...any) string
}

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
}

type RouterCreator

type RouterCreator func(*Slim) Router

type Slim

type Slim struct {

	// TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by
	// that platform, for example to determine the client IP
	TrustedPlatform string

	NewContextFunc       func(pathParamAllocSize int) EditableContext // 自定义 `slim.Context` 构造函数
	ErrorHandler         ErrorHandlerFunc
	Filesystem           fs.FS // 静态资源文件系统,默认值 `os.DirFS(".")`。
	Binder               Binder
	Validator            Validator
	Renderer             Renderer // 自定义模板渲染器
	JSONSerializer       serde.Serializer
	XMLSerializer        serde.Serializer
	Logger               Logger
	Debug                bool     // 是否开启调试模式
	MultipartMemoryLimit int64    // 文件上传大小限制
	PrettyIndent         string   // json/xml 格式化缩进
	JSONPCallbacks       []string // jsonp 回调函数
	IPExtractor          IPExtractor
	// 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 an empty `Context` instance from the pool. You must return the context by calling `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) 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) Negotiator

func (s *Slim) Negotiator() *nego.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 returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.

func (*Slim) ResetRouterCreator

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

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

func (*Slim) Reverse

func (s *Slim) Reverse(name string, params ...any) string

Reverse generates a URL from route name and provided parameters. In case when Slim serves multiple hosts/domains use `s.Routers()["domain2.site"].Reverse()` to get specific host URL.

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

func (s *Slim) Routes() []Route

Routes returns the registered routes for default router. In case when Slim serves multiple hosts/domains use `s.Routers()["domain2.site"].Routes()` to get specific host routes.

func (*Slim) ServeHTTP

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

ServeHTTP implements `http.Handler` interface, which serves HTTP requests.

func (*Slim) SetNegotiator

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

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

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

func (s *Slim) URI(h HandlerFunc, params ...any) string

URI generates a URI from handler. In case when Slim serves multiple hosts/domains use `s.Routers()["domain2.site"].Reverse()` to get specific host URL.

func (*Slim) Use

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

Use adds middleware to the chain which is run before router.

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 TagFunc

type TagFunc func(w io.Writer, tag string) (int, error)

TagFunc can be used as a substitution value in the map passed to Execute*. Execute* functions pass tag (placeholder) name in 'tag' argument.

TagFunc must be safe to call from concurrently running goroutines.

TagFunc must write contents to w and return the number of bytes written.

type TemplateRenderer

type TemplateRenderer struct {
	Template interface {
		ExecuteTemplate(wr io.Writer, name string, data any) error
	}
}

TemplateRenderer is helper to ease creating renderers for `html/template` and `text/template` packages. Example usage:

	e.Renderer = &slim.TemplateRenderer{
		Template: template.Must(template.ParseGlob("templates/*.html")),
	}

  e.Renderer = &slim.TemplateRenderer{
		Template: template.Must(template.New("hello").Parse("Hello, {{.}}!")),
	}

func (*TemplateRenderer) Render

func (t *TemplateRenderer) Render(_ Context, w io.Writer, name string, data any) error

Render renders the template with given data.

type Validator

type Validator interface {
	Validate(i any) error
}

Validator is the interface that wraps the Validate function.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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