handler

package
v0.2.6 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2023 License: MIT Imports: 20 Imported by: 8

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	AccessLogComponentName = "web.accessLog"
)
View Source
var (
	DefaultNegotiateFormat = []string{binding.MIMEJSON, binding.MIMEXML}
)
View Source
var (
	ErrRecovery = errors.New("internal server error")
)

Functions

func AbortWithError added in v0.2.6

func AbortWithError(c *gin.Context, code int, err error)

AbortWithError gin context's AbortWithError prevent to reset response header, so we need to replace it

func DefaultSkipper added in v0.0.3

func DefaultSkipper(c *gin.Context) bool

DefaultSkipper returns false which processes the middleware.

func FormatResponseError added in v0.0.3

func FormatResponseError(code int, err error) gin.H

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 HandleRecoverError(c *gin.Context, p any, stackSkip int)

func NegotiateResponse added in v0.1.0

func NegotiateResponse(c *gin.Context, code int, data any, offered []string)

NegotiateResponse calls different Render according to acceptably Accept format.

no support format described:

protobuf: gin.H is not protoreflect.ProtoMessage

func PathSkip added in v0.2.2

func PathSkip(list []string, url *url.URL) bool

PathSkip returns a skipper function that skips middleware if the request path

func SetContextError added in v0.0.3

func SetContextError(c *gin.Context, code int, err error)

SetContextError set the error to Context,and the error will be handled by ErrorHandleMiddleware

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 (*ErrorHandleMiddleware) Name added in v0.0.3

func (em *ErrorHandleMiddleware) Name() string

func (*ErrorHandleMiddleware) Shutdown added in v0.0.3

func (em *ErrorHandleMiddleware) Shutdown(_ context.Context) error

type ErrorParser added in v0.0.3

type ErrorParser func(c *gin.Context, public error) (int, any)

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

func (*JWTMiddleware) Shutdown added in v0.0.3

func (mw *JWTMiddleware) Shutdown(_ context.Context) error

Shutdown no need to do anything

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

type KeyAuthErrorHandler func(c *gin.Context, err error) error

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

func (*KeyAuthMiddleware) Shutdown added in v0.1.0

func (mw *KeyAuthMiddleware) Shutdown(_ context.Context) error

Shutdown nothing to do

type KeyAuthValidator added in v0.1.0

type KeyAuthValidator func(c *gin.Context, keyAuth string) (bool, error)

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

func (*LoggerMiddleware) Shutdown added in v0.0.3

func (h *LoggerMiddleware) Shutdown(_ context.Context) error

Shutdown does nothing for logger

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

func (*Manager) Shutdown

func (m *Manager) Shutdown(ctx context.Context) error

Shutdown a handler if handler base on file,net such as need to release resource

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 (*RecoveryMiddleware) Name added in v0.0.3

func (h *RecoveryMiddleware) Name() string

func (*RecoveryMiddleware) Shutdown added in v0.0.3

func (h *RecoveryMiddleware) Shutdown(_ context.Context) error

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

func (*SimpleMiddleware) Shutdown added in v0.0.3

func (s *SimpleMiddleware) Shutdown(_ context.Context) error

type Skipper added in v0.0.3

type Skipper func(c *gin.Context) bool

Skipper defines a function to skip middleware. Returning true skips processing the middleware.

type ValuesExtractor added in v0.0.3

type ValuesExtractor func(c *gin.Context) ([]string, error)

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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