Documentation ¶
Index ¶
- Constants
- Variables
- func AbortWithError(c *gin.Context, code int, err error)
- func DefaultSkipper(c *gin.Context) bool
- func DerivativeContextWithValue(c *gin.Context, key, val any) bool
- func FormatResponseError(code int, err error) gin.H
- func GetDerivativeContext(c *gin.Context) context.Context
- 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(pm map[string]struct{}, url *url.URL) bool
- func SetContextError(c *gin.Context, code int, err error)
- func SetDerivativeContext(c *gin.Context, ctx context.Context)
- func SetErrorMap(cm map[int]string, em map[string]string)
- func StringsToMap(list []string) map[string]struct{}
- type ErrorHandleConfig
- type ErrorHandleMiddleware
- type ErrorParser
- type JWTConfig
- type JWTMiddleware
- type KeyAuthConfig
- type KeyAuthErrorHandler
- type KeyAuthMiddleware
- type KeyAuthValidator
- type LoggerConfig
- type LoggerMiddleware
- type Middleware
- type MiddlewareApplyFunc
- type MiddlewareInitConfigFunc
- type MiddlewareNewFunc
- type MiddlewareOption
- type MiddlewareOptions
- type RecoveryMiddleware
- type Shutdown
- 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 ¶
const ( RecoverName = "recovery" JWTName = "jwt" AccessLogName = "accessLog" ErrorHandlerName = "errorHandle" GZipName = "gzip" KeyAuthName = "keyAuth" CORSName = "cors" CSRFName = "csrf" )
Variables ¶
var ( AccessLogComponentName = "web.accessLog" LoggerFieldSkip = zap.Skip() )
var DefaultErrorFormater = FormatResponseError
DefaultErrorFormater is the default error formater
var (
DefaultNegotiateFormat = []string{binding.MIMEJSON}
)
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 DerivativeContextWithValue ¶ added in v0.4.0
DerivativeContextWithValue try to set a ctx to the derivative context slot in gin.Context, if no existing set to request.Context and return false.
func FormatResponseError ¶ added in v0.0.3
FormatResponseError converts a http error to gin.H
func GetDerivativeContext ¶ added in v0.4.0
GetDerivativeContext get the derivative context from gin.Context, return gin.Context if no existing
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.
HTTP Status Code behavior:
1. response has sent cannot change it. 2. if code is not default, use it. 3. if code is default, use passed code.
no support format described:
protobuf: gin.H is not protoreflect.ProtoMessage
func PathSkip ¶ added in v0.2.2
PathSkip returns a skipper function that skips middleware if the request path
func SetContextError ¶ added in v0.0.3
SetContextError set the error to Context, and the error will be handled by ErrorHandleMiddleware
func SetDerivativeContext ¶ added in v0.4.0
SetDerivativeContext set the derivative context to gin.Context
func SetErrorMap ¶ added in v0.5.3
SetErrorMap set the error code map and error message map for ErrorHandler.
func StringsToMap ¶ added in v0.4.0
StringsToMap convert a string slice to a map
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 message you want mask all private error, it will not mask public error. // see gin.ErrorType 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/pkg/conf" "github.com/tsingsun/woocoo/web/handler" ) func main() { hdl := handler.NewErrorHandle(handler.WithMiddlewareConfig(func(config any) { codeMap := map[uint64]any{ 10000: "miss required param", 10001: "invalid param", } errorMap := map[interface{ Error() string }]string{ http.ErrBodyNotAllowed: "username/password not correct", } c := config.(*handler.ErrorHandleConfig) c.Accepts = "application/json,application/xml" c.Message = "internal error" c.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, you can pass a custom conf.Configuration gin.Default().Use(hdl.ApplyFunc(conf.New())) }
Output:
func NewErrorHandle ¶ added in v0.4.0
func NewErrorHandle(opts ...MiddlewareOption) *ErrorHandleMiddleware
NewErrorHandle is the error handle middleware
func (*ErrorHandleMiddleware) ApplyFunc ¶ added in v0.0.3
func (mw *ErrorHandleMiddleware) ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc
func (*ErrorHandleMiddleware) Name ¶ added in v0.0.3
func (mw *ErrorHandleMiddleware) Name() string
type ErrorParser ¶ added in v0.0.3
ErrorParser is the error parser, public error adopt by private error to show to the 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] = DefaultErrorFormater(code, e.Err) case gin.ErrorTypePrivate: if public == nil { errs[i] = DefaultErrorFormater(code, e.Err) } else { errs[i] = DefaultErrorFormater(code, public) } default: errs[i] = DefaultErrorFormater(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 // LogoutHandler defines a function which is executed for user logout system.It clears 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 // 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 NewJWT ¶ added in v0.4.0
func NewJWT(opts ...MiddlewareOption) *JWTMiddleware
NewJWT constructs a new JWT struct with supplied options.
func (*JWTMiddleware) ApplyFunc ¶ added in v0.0.3
func (mw *JWTMiddleware) ApplyFunc(cfg *conf.Configuration) gin.HandlerFunc
func (*JWTMiddleware) HandleToken ¶ added in v0.4.0
func (mw *JWTMiddleware) HandleToken(ctx context.Context, authStr string) (token *jwt.Token, err error)
HandleToken parse and check the token string. You can call it when do out of gin context
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 NewKeyAuth ¶ added in v0.4.0
func NewKeyAuth(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"` Level zapcore.Level `json:"level" yaml:"level"` Tags []loggerTag }
func (*LoggerConfig) BuildTag ¶ added in v0.5.2
func (h *LoggerConfig) BuildTag(format string)
type LoggerMiddleware ¶ added in v0.0.3
type LoggerMiddleware struct {
// contains filtered or unexported fields
}
LoggerMiddleware is a middleware that logs each request.
func NewAccessLog ¶ added in v0.4.0
func NewAccessLog() *LoggerMiddleware
NewAccessLog 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 NewAccessLog middleware
func (*LoggerMiddleware) Name ¶ added in v0.0.3
func (h *LoggerMiddleware) Name() string
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 }
Middleware is an instance to build middleware for web application.
func AccessLog ¶ added in v0.0.3
func AccessLog() Middleware
AccessLog is the access logger middleware apply function. see MiddlewareNewFunc
func CORS ¶ added in v0.4.0
func CORS() Middleware
CORS Cross-Origin Resource Sharing (CORS) support
func ErrorHandle ¶ added in v0.0.3
func ErrorHandle() Middleware
ErrorHandle is the error handle middleware apply function. see MiddlewareNewFunc
func JWT ¶ added in v0.0.3
func JWT() Middleware
JWT is the jwt middleware apply function. see MiddlewareNewFunc
func KeyAuth ¶ added in v0.1.0
func KeyAuth() Middleware
KeyAuth is the keyauth middleware apply function. see MiddlewareNewFunc
func Recovery ¶ added in v0.0.3
func Recovery() Middleware
Recovery is the recovery middleware apply function. see MiddlewareNewFunc
type MiddlewareApplyFunc ¶ added in v0.0.3
type MiddlewareApplyFunc func(cfg *conf.Configuration) gin.HandlerFunc
MiddlewareApplyFunc defines a function to initial new middleware by a configuration
type MiddlewareInitConfigFunc ¶ added in v0.4.0
type MiddlewareInitConfigFunc func(config any)
MiddlewareInitConfigFunc is the function that gets the middleware config and mutate.
if you want the middleware config passes to the middleware, you can use this function, for example, in Middleware.ApplyFunc, the config is set up by the configuration, you cannot change it. in this case,you can use this function to change the config before ApplyFunc.
parameter config must be a pointer type.
type MiddlewareNewFunc ¶ added in v0.4.0
type MiddlewareNewFunc func() Middleware
MiddlewareNewFunc defines a function to initial new middleware
func WrapMiddlewareApplyFunc ¶ added in v0.4.0
func WrapMiddlewareApplyFunc(name string, applyFunc MiddlewareApplyFunc) MiddlewareNewFunc
WrapMiddlewareApplyFunc wraps a MiddlewareApplyFunc to MiddlewareNewFunc
type MiddlewareOption ¶ added in v0.0.3
type MiddlewareOption func(o *MiddlewareOptions)
func WithMiddlewareConfig ¶ added in v0.0.3
func WithMiddlewareConfig(configFunc MiddlewareInitConfigFunc) MiddlewareOption
WithMiddlewareConfig use to change the default middleware config
type MiddlewareOptions ¶ added in v0.4.0
type MiddlewareOptions struct { // set the function that gets the default middleware config, so you can change the default config ConfigFunc MiddlewareInitConfigFunc }
MiddlewareOptions middleware options for middleware to implement advanced features.if middleware config initial from Configuration, you don't need to use this.
you need to register the middleware again if you use MiddlewareOption to change the middleware behavior. example:
middleware := handler.NewJWT(handler.WithMiddlewareConfig(func() any { return &jwt.Config{...} })) web.RegisterMiddleware(middleware)
func NewMiddlewareOption ¶ added in v0.4.0
func NewMiddlewareOption(options ...MiddlewareOption) MiddlewareOptions
NewMiddlewareOption apply the options to MiddlewareOptions
type RecoveryMiddleware ¶ added in v0.0.3
type RecoveryMiddleware struct { }
RecoveryMiddleware is a middleware that recovers from panics anywhere in the chain and handles the control to the centralized HTTPErrorHandler.
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.
func PathSkipper ¶ added in v0.4.0
PathSkipper returns a Skipper function that skips processing 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 functions that extract values from the request header. valuePrefix is a parameter to remove the 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 the case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove is `Basic `. In the case of NewJWT tokens `Authorization: Bearer <token>` prefix is `Bearer `. If the 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.