Documentation ¶
Index ¶
- Variables
- func AbortWithError(c *gin.Context, code int, err error)
- func DefaultSkipper(c *gin.Context) bool
- func FormatResponseError(code int, err error) gin.H
- func GetLogCarrierFromGinContext(c *gin.Context) *log.FieldCarrier
- func HandleRecoverError(c *gin.Context, p any, stackSkip int)
- func NegotiateResponse(c *gin.Context, code int, data any, offered []string)
- func PathSkip(list []string, url *url.URL) bool
- func SetContextError(c *gin.Context, code int, err error)
- type ErrorHandleConfig
- type ErrorHandleMiddleware
- type ErrorParser
- type JWTConfig
- type JWTMiddleware
- type KeyAuthConfig
- type KeyAuthErrorHandler
- type KeyAuthMiddleware
- type KeyAuthValidator
- type LoggerConfig
- type LoggerMiddleware
- type Manager
- type Middleware
- type MiddlewareApplyFunc
- type MiddlewareDefaultConfigFunc
- type MiddlewareOption
- type RecoveryMiddleware
- type SimpleMiddleware
- type Skipper
- type ValuesExtractor
- func CreateExtractors(lookups string, authScheme string) ([]ValuesExtractor, error)
- func ValuesFromCookie(name string) ValuesExtractor
- func ValuesFromForm(name string) ValuesExtractor
- func ValuesFromHeader(header string, valuePrefix string) ValuesExtractor
- func ValuesFromParam(param string) ValuesExtractor
- func ValuesFromQuery(param string) ValuesExtractor
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var (
AccessLogComponentName = "web.accessLog"
)
var (
ErrRecovery = errors.New("internal server error")
)
Functions ¶
func AbortWithError ¶ added in v0.2.6
AbortWithError gin context's AbortWithError prevent to reset response header, so we need to replace it
func DefaultSkipper ¶ added in v0.0.3
DefaultSkipper returns false which processes the middleware.
func FormatResponseError ¶ added in v0.0.3
FormatResponseError converts a http error to gin.H
func GetLogCarrierFromGinContext ¶ added in v0.1.0
func GetLogCarrierFromGinContext(c *gin.Context) *log.FieldCarrier
func HandleRecoverError ¶ added in v0.0.3
func NegotiateResponse ¶ added in v0.1.0
NegotiateResponse calls different Render according to acceptably Accept format.
no support format described:
protobuf: gin.H is not protoreflect.ProtoMessage
Types ¶
type ErrorHandleConfig ¶ added in v0.0.3
type ErrorHandleConfig struct { // NegotiateFormat is the offered http media type format for errors. // formats split by comma, such as "application/json,application/xml" Accepts string `json:"accepts" yaml:"accepts"` NegotiateFormat []string `json:"-" yaml:"-"` ErrorParser ErrorParser `json:"-" yaml:"-"` // Message is the string while the error is private Message string `json:"message" yaml:"message"` }
ErrorHandleConfig is the config for error handle
type ErrorHandleMiddleware ¶ added in v0.0.3
type ErrorHandleMiddleware struct {
// contains filtered or unexported fields
}
ErrorHandleMiddleware is the middleware for error handle to format the errors to client
Example (CustomErrorParser) ¶
ExampleErrorHandleMiddleware_customErrorParser is the example for customer ErrorHandle
package main import ( "github.com/gin-gonic/gin" "github.com/tsingsun/woocoo/web/handler" ) func main() { hdl := handler.ErrorHandle(handler.WithMiddlewareConfig(func() any { codeMap := map[uint64]any{ 10000: "miss required param", 10001: "invalid param", } errorMap := map[interface{ Error() string }]string{ http.ErrBodyNotAllowed: "username/password not correct", } return &handler.ErrorHandleConfig{ Accepts: "application/json,application/xml", Message: "internal error", ErrorParser: func(c *gin.Context, public error) (int, any) { var errs = make([]gin.H, len(c.Errors)) for i, e := range c.Errors { if txt, ok := codeMap[uint64(e.Type)]; ok { errs[i] = gin.H{"code": i, "message": txt} continue } if txt, ok := errorMap[e.Err]; ok { errs[i] = gin.H{"code": i, "message": txt} continue } errs[i] = gin.H{"code": i, "message": e.Error()} } return 0, errs }, } })) // use in web server gin.Default().Use(hdl.ApplyFunc(nil)) }
Output:
func ErrorHandle ¶ added in v0.0.3
func ErrorHandle(opts ...MiddlewareOption) *ErrorHandleMiddleware
ErrorHandle is the error handle middleware
func (*ErrorHandleMiddleware) ApplyFunc ¶ added in v0.0.3
func (em *ErrorHandleMiddleware) ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc
func (*ErrorHandleMiddleware) Name ¶ added in v0.0.3
func (em *ErrorHandleMiddleware) Name() string
type ErrorParser ¶ added in v0.0.3
ErrorParser is the error parser,public error adopt by private error to show to client.
var DefaultErrorParser ErrorParser = func(c *gin.Context, public error) (int, any) { var errs = make([]gin.H, len(c.Errors)) var code = c.Writer.Status() if code == http.StatusOK { code = http.StatusInternalServerError } for i, e := range c.Errors { switch e.Type { case gin.ErrorTypePublic: errs[i] = FormatResponseError(code, e.Err) case gin.ErrorTypePrivate: if public == nil { errs[i] = FormatResponseError(code, e.Err) } else { errs[i] = FormatResponseError(code, public) } default: errs[i] = FormatResponseError(int(e.Type), e.Err) } } return code, gin.H{"errors": errs} }
type JWTConfig ¶ added in v0.0.3
type JWTConfig struct { auth.JWTOptions `json:",inline" yaml:",inline"` Skipper Skipper // Exclude is a list of http paths to exclude from JWT auth // // path format must same as url.URL.Path started with "/" and ended with "/" Exclude []string `json:"exclude" yaml:"exclude"` // TokenLookupFuncs defines a list of user-defined functions that extract JWT token from the given context. // This is one of the two options to provide a token extractor. // The order of precedence is user-defined TokenLookupFuncs, and TokenLookup. // You can also provide both if you want. TokenLookupFuncs []ValuesExtractor // SuccessHandler defines a function which is executed for a valid token before middleware chain continues with next // middleware or handler. SuccessHandler func(c *gin.Context) // LogoutHandler defines a function which is executed for user logout system.It clear something like cache. LogoutHandler func(*gin.Context) // ErrorHandler defines a function which is executed for an invalid token. // It may be used to define a custom JWT error and abort the request.like use: // c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"}) ErrorHandler func(c *gin.Context, err error) error // TokenStoreKey is the name of the cache driver,default is "redis". // When this option is used, requirements : token cache KEY that uses the JWT ID. TokenStoreKey string `json:"tokenStoreKey" yaml:"TokenStoreKey"` // WithPrincipalContext defines a function which is Principal creator and store principal in context. // // Use GeneratePrincipal by default. You can use your own function to create principal. WithPrincipalContext func(c *gin.Context, token *jwt.Token) error }
type JWTMiddleware ¶ added in v0.0.3
type JWTMiddleware struct { Config *JWTConfig // TokenStore is the cache for store token key. TokenStore cache.Cache // contains filtered or unexported fields }
JWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response is returned. On success, the wrapped middleware is called, and the userID is made available as c.Get("userID").(string). Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX
func JWT ¶ added in v0.0.3
func JWT(opts ...MiddlewareOption) *JWTMiddleware
func (*JWTMiddleware) ApplyFunc ¶ added in v0.0.3
func (mw *JWTMiddleware) ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc
func (*JWTMiddleware) Name ¶ added in v0.0.3
func (mw *JWTMiddleware) Name() string
type KeyAuthConfig ¶ added in v0.1.0
type KeyAuthConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper // Exclude is a list of http paths to exclude from key auth Exclude []string `json:"exclude" yaml:"exclude"` // KeyLookupFuncs defines a list of user-defined functions that extract key token from the given context. // This is one of the two options to provide a token extractor. // The order of precedence is user-defined KeyLookupFuncs, and KeyLookup. // You can also provide both if you want. KeyLookupFuncs []ValuesExtractor // KeyLookup is a string in the form of "<source>:<name>" that is used // to extract key from the request. // Optional. Default value "header:Authorization". // Possible values: // - "header:<name>" // - "query:<name>" // - "cookie:<name>" // - "form:<name>" KeyLookup string `json:"keyLookup" yaml:"keyLookup"` // AuthScheme to be used in the Authorization header. AuthScheme string `json:"authScheme" yaml:"authScheme"` // Validator is a function to validate key token.You can use it to check the token is valid or not,then set // the user info to the context. Validator KeyAuthValidator // ErrorHandler is a function which is executed when an error occurs during the middleware processing. ErrorHandler KeyAuthErrorHandler }
type KeyAuthErrorHandler ¶ added in v0.1.0
KeyAuthErrorHandler defines a function which is executed for an invalid token.
type KeyAuthMiddleware ¶ added in v0.1.0
type KeyAuthMiddleware struct {
// contains filtered or unexported fields
}
func KeyAuth ¶ added in v0.1.0
func KeyAuth(opts ...MiddlewareOption) *KeyAuthMiddleware
func (*KeyAuthMiddleware) ApplyFunc ¶ added in v0.1.0
func (mw *KeyAuthMiddleware) ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc
func (*KeyAuthMiddleware) Name ¶ added in v0.1.0
func (mw *KeyAuthMiddleware) Name() string
type KeyAuthValidator ¶ added in v0.1.0
KeyAuthValidator is a function that validates key token and returns
type LoggerConfig ¶ added in v0.0.3
type LoggerConfig struct { Skipper Skipper Exclude []string `json:"exclude" yaml:"exclude"` // Tags to construct the logger format. // // - id (Request ID or trace ID) // - remoteIp // - uri // - host // - method // - path // - protocol // - referer // - userAgent // - status // - error // - latency (In nanoseconds) // - latencyHuman (Human readable) // - bytesIn (Bytes received) // - bytesOut (Bytes sent) // - header:<NAME> // - query:<NAME> // - form:<NAME> // - context:<NAME> // // // Optional. Default value DefaultLoggerConfig.Format. Format string `json:"format" yaml:"format"` // contains filtered or unexported fields }
type LoggerMiddleware ¶ added in v0.0.3
type LoggerMiddleware struct {
// contains filtered or unexported fields
}
LoggerMiddleware is a middleware that logs each request.
func AccessLog ¶ added in v0.0.3
func AccessLog() *LoggerMiddleware
AccessLog a new LoggerMiddleware,it is for handler registry
func (*LoggerMiddleware) ApplyFunc ¶ added in v0.0.3
func (h *LoggerMiddleware) ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc
ApplyFunc build a gin.HandlerFunc for AccessLog middleware
func (*LoggerMiddleware) Name ¶ added in v0.0.3
func (h *LoggerMiddleware) Name() string
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager is a middleware manager
func NewManager ¶
func NewManager() *Manager
NewManager creates a new middleware manager, initialize common useful middlewares.
func (*Manager) Get ¶ added in v0.0.3
func (m *Manager) Get(name string) (Middleware, bool)
Get returns a handler middleware by name
func (*Manager) RegisterHandlerFunc ¶
func (m *Manager) RegisterHandlerFunc(name string, handler Middleware)
RegisterHandlerFunc registry a handler middleware
you can override exists handler
type Middleware ¶ added in v0.0.3
type Middleware interface { // Name returns the name of the handler. Name() string // ApplyFunc return a gin's handler function by a configuration ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc // Shutdown the handler,usually call in server quit. some base on file,network may need release the resource Shutdown(ctx context.Context) error }
Middleware is an instance to build a echo middleware for web application.
type MiddlewareApplyFunc ¶ added in v0.0.3
type MiddlewareApplyFunc func(cfg *conf.Configuration) gin.HandlerFunc
type MiddlewareDefaultConfigFunc ¶ added in v0.0.3
type MiddlewareDefaultConfigFunc func() any
MiddlewareDefaultConfigFunc is the function that get the default middleware config.
if you want the middleware config pass to the middleware,you can use this function. for example: in Middleware.ApplyFunc, the config is set up by the configuration,you can not change it.in this case,you can use this function. function return value is the pointer of the middleware config.
type MiddlewareOption ¶ added in v0.0.3
type MiddlewareOption func(o *middlewareOptions)
func WithMiddlewareConfig ¶ added in v0.0.3
func WithMiddlewareConfig(configFunc MiddlewareDefaultConfigFunc) MiddlewareOption
WithMiddlewareConfig use to change the default middleware config
type RecoveryMiddleware ¶ added in v0.0.3
type RecoveryMiddleware struct { }
RecoveryMiddleware is a middleware which recovers from panics anywhere in the chain and handles the control to the centralized HTTPErrorHandler.
func Recovery ¶ added in v0.0.3
func Recovery() *RecoveryMiddleware
func (*RecoveryMiddleware) ApplyFunc ¶ added in v0.0.3
func (h *RecoveryMiddleware) ApplyFunc(_ *conf.Configuration) gin.HandlerFunc
func (*RecoveryMiddleware) Name ¶ added in v0.0.3
func (h *RecoveryMiddleware) Name() string
type SimpleMiddleware ¶ added in v0.0.3
type SimpleMiddleware struct {
// contains filtered or unexported fields
}
SimpleMiddleware is a convenience to build middleware by name and gin.HandlerFunc
func NewSimpleMiddleware ¶ added in v0.0.3
func NewSimpleMiddleware(name string, applyFunc MiddlewareApplyFunc) *SimpleMiddleware
NewSimpleMiddleware returns a new SimpleMiddleware instance.
SimpleMiddleware shutdowns method is empty. cfg: the configuration of the middleware, usually pass by web server.
func (*SimpleMiddleware) ApplyFunc ¶ added in v0.0.3
func (s *SimpleMiddleware) ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc
func (*SimpleMiddleware) Name ¶ added in v0.0.3
func (s *SimpleMiddleware) Name() string
type Skipper ¶ added in v0.0.3
Skipper defines a function to skip middleware. Returning true skips processing the middleware.
type ValuesExtractor ¶ added in v0.0.3
ValuesExtractor defines a function for extracting values (keys/tokens) from the given context.
func CreateExtractors ¶ added in v0.0.3
func CreateExtractors(lookups string, authScheme string) ([]ValuesExtractor, error)
CreateExtractors creates a list of extractors based on the given list of extractor names.
func ValuesFromCookie ¶ added in v0.0.3
func ValuesFromCookie(name string) ValuesExtractor
ValuesFromCookie returns a function that extracts values from the named cookie.
func ValuesFromForm ¶ added in v0.0.3
func ValuesFromForm(name string) ValuesExtractor
ValuesFromForm returns a function that extracts values from the form field.
func ValuesFromHeader ¶ added in v0.0.3
func ValuesFromHeader(header string, valuePrefix string) ValuesExtractor
ValuesFromHeader returns a functions that extracts values from the request header. valuePrefix is parameter to remove first part (prefix) of the extracted value. This is useful if header value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we want to remove is `<auth-scheme> ` note the space at the end. In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `. In case of JWT tokens `Authorization: Bearer <token>` prefix is `Bearer `. If prefix is left empty the whole value is returned.
func ValuesFromParam ¶ added in v0.0.3
func ValuesFromParam(param string) ValuesExtractor
ValuesFromParam returns a function that extracts values from the url param string.
func ValuesFromQuery ¶ added in v0.0.3
func ValuesFromQuery(param string) ValuesExtractor
ValuesFromQuery returns a function that extracts values from the query string.