xgin

package module
v0.0.0-...-2f11a2c Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2023 License: MIT Imports: 29 Imported by: 0

README

xgin

Dependencies

  • github.com/Aoi-hosizora/ahlib
  • github.com/gin-gonic/gin (Note: DO NOT update to v1.9.0)
  • github.com/go-playground/validator/v10
  • github.com/sirupsen/logrus
  • golang.org/x/sys

Documents

Types
  • type NewEngineOption func
  • type DumpRequestOption func
  • type SwaggerOptions struct
  • type SwaggerOption func
  • type DebugPrintRouteFuncType func
  • type RouterDecodeError struct
  • type TranslatableError interface
  • type TranslateOption func
  • type LoggerOption func
  • type ResponseLoggerParam struct
  • type RecoveryLoggerParam struct
Variables
  • var FormatResponseFunc func(p *ResponseLoggerParam) string
  • var FieldifyResponseFunc func(p *ResponseLoggerParam) logrus.Fields
  • var FormatRecoveryFunc func(p *RecoveryLoggerParam) string
  • var FieldifyRecoveryFunc func(p *RecoveryLoggerParam) logrus.Fields
Constants
  • None
Functions
  • func WithMode(mode string) NewEngineOption
  • func WithDebugPrintRouteFunc(debugPrintRouteFunc DebugPrintRouteFuncType) NewEngineOption
  • func WithDefaultWriter(defaultWriter io.Writer) NewEngineOption
  • func WithDefaultErrorWriter(defaultErrorWriter io.Writer) NewEngineOption
  • func WithRedirectTrailingSlash(redirectTrailingSlash bool) NewEngineOption
  • func WithRedirectFixedPath(redirectFixedPath bool) NewEngineOption
  • func WithHandleMethodNotAllowed(handleMethodNotAllowed bool) NewEngineOption
  • func WithForwardedByClientIP(forwardedByClientIP bool) NewEngineOption
  • func WithUseRawPath(useRawPath bool) NewEngineOption
  • func WithUnescapePathValues(unescapePathValues bool) NewEngineOption
  • func WithRemoveExtraSlash(removeExtraSlash bool) NewEngineOption
  • func WithRemoteIPHeaders(remoteIPHeaders []string) NewEngineOption
  • func WithTrustedPlatform(trustedPlatform string) NewEngineOption
  • func WithMaxMultipartMemory(maxMultipartMemory int64) NewEngineOption
  • func WithUseH2C(useH2C bool) NewEngineOption
  • func WithContextWithFallback(contextWithFallback bool) NewEngineOption
  • func WithSecureJSONPrefix(secureJSONPrefix string) NewEngineOption
  • func WithNoRoute(noRoute gin.HandlersChain) NewEngineOption
  • func WithNoMethod(noMethod gin.HandlersChain) NewEngineOption
  • func WithTrustedProxies(trustedProxies []string) NewEngineOption
  • func NewEngine(options ...NewEngineOption) *gin.Engine
  • func NewEngineSilently(options ...NewEngineOption) *gin.Engine
  • func WithIgnoreRequestLine(ignore bool) DumpRequestOption
  • func WithRetainHeaders(headers ...string) DumpRequestOption
  • func WithIgnoreHeaders(headers ...string) DumpRequestOption
  • func WithSecretHeaders(headers ...string) DumpRequestOption
  • func WithSecretPlaceholder(placeholder string) DumpRequestOption
  • func DumpRequest(c *gin.Context, options ...DumpRequestOption) []string
  • func DumpHttpRequest(req *http.Request, options ...DumpRequestOption) []string
  • func RedirectHandler(code int, location string) gin.HandlerFunc
  • func WrapPprof(router gin.IRouter)
  • func WrapPprofSilently(router gin.IRouter)
  • func WithSwaggerIndexHtmlRouteName(indexHtmlRouteName string) SwaggerOption
  • func WithSwaggerDocJsonRouteName(docJsonRouteName string) SwaggerOption
  • func WithSwaggerConfigJsonRouteName(configJsonRouteName string) SwaggerOption
  • func WithSwaggerEnableRedirect(enableRedirect bool) SwaggerOption
  • func WithSwaggerDeepLinking(deepLinking bool) SwaggerOption
  • func WithSwaggerDisplayOperationId(displayOperationId bool) SwaggerOption
  • func WithSwaggerDefaultModelsExpandDepth(defaultModelsExpandDepth int) SwaggerOption
  • func WithSwaggerDefaultModelExpandDepth(defaultModelExpandDepth int) SwaggerOption
  • func WithSwaggerDefaultModelRendering(defaultModelRendering string) SwaggerOption
  • func WithSwaggerDisplayRequestDuration(displayRequestDuration bool) SwaggerOption
  • func WithSwaggerDocExpansion(docExpansion string) SwaggerOption
  • func WithSwaggerMaxDisplayedTags(maxDisplayedTags int) SwaggerOption
  • func WithSwaggerOperationsSorter(operationsSorter string) SwaggerOption
  • func WithSwaggerShowExtensions(showExtensions bool) SwaggerOption
  • func WithSwaggerShowCommonExtensions(showCommonExtensions bool) SwaggerOption
  • func WithSwaggerTagsSorter(tagsSorter string) SwaggerOption
  • func ReadSwaggerDoc() []byte
  • func WrapSwagger(router gin.IRouter, swaggerDocGetter func() []byte, swaggerOptions ...SwaggerOption)
  • func WrapSwaggerSilently(router gin.IRouter, swaggerDocGetter func() []byte, swaggerOptions ...SwaggerOption)
  • func GetTrustedProxies(engine *gin.Engine) []string
  • func HideDebugLogging() (restoreFn func())
  • func HideDebugPrintRoute() (restoreFn func())
  • func SilentPrintRouteFunc(_, _, _ string, _ int)
  • func DefaultPrintRouteFunc(httpMethod, absolutePath, handlerName string, numHandlers int)
  • func DefaultColorizedPrintRouteFunc(httpMethod, absolutePath, handlerName string, numHandlers int)
  • func NewRouterDecodeError(field string, input string, err error, message string) *RouterDecodeError
  • func ListenAndServeWithReuse(ctx context.Context, server *http.Server) error
  • func ReuseListenControl(_, _ string, c syscall.RawConn) error
  • func GetValidatorEngine() (*validator.Validate, error)
  • func GetValidatorTranslator(locale xvalidator.LocaleTranslator, registerFn xvalidator.TranslationRegisterHandler) (xvalidator.UtTranslator, error)
  • func GetValidatorEnglishTranslator() (xvalidator.UtTranslator, error)
  • func SetGlobalTranslator(translator xvalidator.UtTranslator)
  • func GetGlobalTranslator() xvalidator.UtTranslator
  • func AddBinding(tag string, fn validator.Func) error
  • func AddTranslation(translator xvalidator.UtTranslator, tag, message string, override bool) error
  • func EnableRegexpBinding() error
  • func EnableRegexpBindingTranslator(translator ut.Translator) error
  • func EnableRFC3339DateBinding() error
  • func EnableRFC3339DateBindingTranslator(translator ut.Translator) error
  • func EnableRFC3339DateTimeBinding() error
  • func EnableRFC3339DateTimeBindingTranslator(translator ut.Translator) error
  • func WithUtTranslator(translator xvalidator.UtTranslator) TranslateOption
  • func WithJsonInvalidUnmarshalError(fn func(*json.InvalidUnmarshalError) (result map[string]string, need4xx bool)) TranslateOption
  • func WithJsonUnmarshalTypeError(fn func(*json.UnmarshalTypeError) (result map[string]string, need4xx bool)) TranslateOption
  • func WithJsonSyntaxError(fn func(*json.SyntaxError) (result map[string]string, need4xx bool)) TranslateOption
  • func WithIoEOFError(fn func(error) (result map[string]string, need4xx bool)) TranslateOption
  • func WithStrconvNumErrorError(fn func(*strconv.NumError) (result map[string]string, need4xx bool)) TranslateOption
  • func WithXginRouterDecodeError(fn func(*RouterDecodeError) (result map[string]string, need4xx bool)) TranslateOption
  • func WithValidatorInvalidTypeError(fn func(*validator.InvalidValidationError) (result map[string]string, need4xx bool)) TranslateOption
  • func WithValidatorFieldsError(fn func(validator.ValidationErrors, xvalidator.UtTranslator) (result map[string]string, need4xx bool)) TranslateOption
  • func WithXvalidatorValidateFieldsError(fn func(*xvalidator.ValidateFieldsError, xvalidator.UtTranslator) (result map[string]string, need4xx bool)) TranslateOption
  • func WithTranslatableError(fn func(TranslatableError) (result map[string]string, need4xx bool)) TranslateOption
  • func WithExtraErrorsTranslate(fn func(error) (result map[string]string, need4xx bool)) TranslateOption
  • func TranslateBindingError(err error, options ...TranslateOption) (result map[string]string, need4xx bool)
  • func WithExtraText(text string) LoggerOption
  • func WithMoreExtraText(text string) LoggerOption
  • func WithExtraFields(fields map[string]interface{}) LoggerOption
  • func WithMoreExtraFields(fields map[string]interface{}) LoggerOption
  • func WithExtraFieldsV(fields ...interface{}) LoggerOption
  • func WithMoreExtraFieldsV(fields ...interface{}) LoggerOption
  • func LogResponseToLogrus(logger *logrus.Logger, c *gin.Context, start, end time.Time, options ...LoggerOption)
  • func LogResponseToLogger(logger logrus.StdLogger, c *gin.Context, start, end time.Time, options ...LoggerOption)
  • func LogRecoveryToLogrus(logger *logrus.Logger, v interface{}, stack xruntime.TraceStack, options ...LoggerOption)
  • func LogRecoveryToLogger(logger logrus.StdLogger, v interface{}, stack xruntime.TraceStack, options ...LoggerOption)
Methods
  • func (r *RouterDecodeError) Error() string
  • func (r *RouterDecodeError) Unwrap() error

Documentation

Index

Constants

View Source
const (
	// NAME represents ahlib-mx package's name.
	NAME = "ahlib-mx/xgin"

	// VERSION represents ahlib-mx package's current version.
	VERSION = "1.6.0"
)

Variables

View Source
var (
	// FormatResponseFunc is a custom ResponseLoggerParam's format function for LogResponseToLogrus and LogResponseToLogger.
	FormatResponseFunc func(p *ResponseLoggerParam) string

	// FieldifyResponseFunc is a custom ResponseLoggerParam's fieldify function for LogResponseToLogrus.
	FieldifyResponseFunc func(p *ResponseLoggerParam) logrus.Fields
)
View Source
var (
	// FormatRecoveryFunc is a custom RecoveryLoggerParam's format function for LogRecoveryToLogrus and LogRecoveryToLogger.
	FormatRecoveryFunc func(p *RecoveryLoggerParam) string

	// FieldifyRecoveryFunc is a custom RecoveryLoggerParam's fieldify function for LogRecoveryToLogrus.
	FieldifyRecoveryFunc func(p *RecoveryLoggerParam) logrus.Fields
)

Functions

func AddBinding

func AddBinding(tag string, fn validator.Func) error

AddBinding registers custom validation function to gin's validator engine. You can use your custom validator.Func or functions from xvalidator package such as xvalidator.RegexpValidator and xvalidator.DateTimeValidator.

Example:

err := xgin.AddBinding("regexp", xvalidator.ParamRegexpValidator())
err := xgin.AddBinding("xxx", func(fl validator.FieldLevel) bool { /* ... */ })

func AddTranslation

func AddTranslation(translator xvalidator.UtTranslator, tag, message string, override bool) error

AddTranslation registers custom validation translation to gin's validator engine, using given tag, message and override flag. Also see xvalidator.DefaultTranslateFunc.

Example:

err := xgin.AddTranslation(translator, "regexp", "{0} must match regexp /{1}/", true)
err := xgin.AddTranslation(translator, "email", "{0} must be an email", true)

func DefaultColorizedPrintRouteFunc

func DefaultColorizedPrintRouteFunc(httpMethod, absolutePath, handlerName string, numHandlers int)

DefaultColorizedPrintRouteFunc is the colorized version of DefaultPrintRouteFunc.

The default format logs like (just like gin.DebugPrintRouteFunc except [Gin] prefix):

[Gin] GET    /debug/pprof/             --> ... (1 handlers)
[Gin] GET    /debug/pprof/threadcreate --> ... (1 handlers)
[Gin] POST   /debug/pprof/symbol       --> ... (1 handlers)
     |------|-------------------------|   |---|
     6 (blue)       25 (blue)              ...

func DefaultPrintRouteFunc

func DefaultPrintRouteFunc(httpMethod, absolutePath, handlerName string, numHandlers int)

DefaultPrintRouteFunc is the default gin.DebugPrintRouteFunc, can be modified by overwriting value to gin.DebugPrintRouteFunc.

The default format logs like (just like gin.DebugPrintRouteFunc except [Gin] prefix):

[Gin] GET    /debug/pprof/             --> ... (1 handlers)
[Gin] GET    /debug/pprof/threadcreate --> ... (1 handlers)
[Gin] POST   /debug/pprof/symbol       --> ... (1 handlers)
     |------|-------------------------|   |---|
        6               25                 ...

func DumpHttpRequest

func DumpHttpRequest(req *http.Request, options ...DumpRequestOption) []string

DumpHttpRequest dumps and formats http.Request to string slice using given DumpRequestOption-s.

func DumpRequest

func DumpRequest(c *gin.Context, options ...DumpRequestOption) []string

DumpRequest dumps and formats http.Request from gin.Context to string slice using given DumpRequestOption-s.

func EnableParamRegexpBinding

func EnableParamRegexpBinding() error

EnableParamRegexpBinding enables parameterized regexp validator to `regexp` binding tag, see xvalidator.ParamRegexpValidator.

func EnableParamRegexpBindingTranslator

func EnableParamRegexpBindingTranslator(translator xvalidator.UtTranslator) error

EnableParamRegexpBindingTranslator enables parameterized regexp validator `regexp`'s translation using given xvalidator.UtTranslator.

func EnableRFC3339DateBinding

func EnableRFC3339DateBinding() error

EnableRFC3339DateBinding enables rfc3339 date validator to `date` binding tag, see xvalidator.DateTimeValidator.

func EnableRFC3339DateBindingTranslator

func EnableRFC3339DateBindingTranslator(translator xvalidator.UtTranslator) error

EnableRFC3339DateBindingTranslator enables rfc3339 date validator `date`'s translation using given xvalidator.UtTranslator.

func EnableRFC3339DateTimeBinding

func EnableRFC3339DateTimeBinding() error

EnableRFC3339DateTimeBinding enables rfc3339 datetime validator to `datetime` binding tag, see xvalidator.DateTimeValidator.

func EnableRFC3339DateTimeBindingTranslator

func EnableRFC3339DateTimeBindingTranslator(translator xvalidator.UtTranslator) error

EnableRFC3339DateTimeBindingTranslator enables rfc3339 datetime validator `datetime`'s translation using given xvalidator.UtTranslator.

func GetGlobalTranslator

func GetGlobalTranslator() xvalidator.UtTranslator

GetGlobalTranslator gets the stored translator by SetGlobalTranslator, it will return nil if this function is called before SetGlobalTranslator.

func GetTrustedProxies

func GetTrustedProxies(engine *gin.Engine) []string

GetTrustedProxies returns trusted proxies string slice from given gin.Engine, returns nil if given nil engine.

func GetValidatorEngine

func GetValidatorEngine() (*validator.Validate, error)

GetValidatorEngine returns gin's binding validator engine, which only supports validator.Validate from github.com/go-playground/validator/v10.

func GetValidatorEnglishTranslator

func GetValidatorEnglishTranslator() (xvalidator.UtTranslator, error)

GetValidatorEnglishTranslator applies and returns English xvalidator.UtTranslator for validator.Validate using given parameters, this is a simplified usage of GetValidatorTranslator(validator, xvalidator.EnLocaleTranslator(), xvalidator.EnTranslationRegisterFunc()). Also see xvalidator.ApplyTranslator.

func GetValidatorTranslator

GetValidatorTranslator applies and returns xvalidator.UtTranslator for validator.Validate using given parameters. Also see xvalidator.ApplyTranslator.

Example:

translator, _ := xgin.GetValidatorTranslator(xvalidator.EnLocaleTranslator(), xvalidator.EnTranslationRegisterFunc())
result := err.(validator.ValidationErrors).Translate(translator)

func HideDebugLogging

func HideDebugLogging() (restoreFn func())

HideDebugLogging hides gin's all logging (gin.DefaultWriter and gin.DefaultErrorWriter) and returns a function to restore this behavior.

func HideDebugPrintRoute

func HideDebugPrintRoute() (restoreFn func())

HideDebugPrintRoute hides gin.DebugPrintRouteFunc logging and returns a function to restore this behavior.

func ListenAndServeWithReuse

func ListenAndServeWithReuse(ctx context.Context, server *http.Server) error

ListenAndServeWithReuse listens given http.Server with ReuseListenControl first, and then call Serve on given http.Server, this function just behave the same as http.Server.ListenAndServe but for ReuseListenControl.

func LogRecoveryToLogger

func LogRecoveryToLogger(logger logrus.StdLogger, v interface{}, stack xruntime.TraceStack, options ...LoggerOption)

LogRecoveryToLogger logs panic message to logrus.StdLogger using given recover returned value and nil-able xruntime.TraceStack.

func LogRecoveryToLogrus

func LogRecoveryToLogrus(logger *logrus.Logger, v interface{}, stack xruntime.TraceStack, options ...LoggerOption)

LogRecoveryToLogrus logs panic message to logrus.Logger using given recover returned value and nil-able xruntime.TraceStack.

func LogResponseToLogger

func LogResponseToLogger(logger logrus.StdLogger, c *gin.Context, start, end time.Time, options ...LoggerOption)

LogResponseToLogger logs gin's request and response information to logrus.StdLogger using given gin.Context and other arguments.

func LogResponseToLogrus

func LogResponseToLogrus(logger *logrus.Logger, c *gin.Context, start, end time.Time, options ...LoggerOption)

LogResponseToLogrus logs gin's request and response information to logrus.Logger using given gin.Context and other arguments.

func NewEngine

func NewEngine(options ...NewEngineOption) *gin.Engine

NewEngine creates a new blank gin.Engine instance with some default settings. Note that WithMode, WithDebugPrintRouteFunc, WithDefaultWriter and WithDefaultErrorWriter options will not change gin's global setting if these options are not given, and will directly update global setting if any valid option is passed.

func NewEngineSilently

func NewEngineSilently(options ...NewEngineOption) *gin.Engine

NewEngineSilently creates a new blank gin.Engine instance with some default settings, without any debug logging.

func RedirectHandler

func RedirectHandler(code int, location string) gin.HandlerFunc

RedirectHandler creates a gin.HandlerFunc that behaviors a redirection with given code (such as http.StatusMovedPermanently or http.StatusTemporaryRedirect) and redirect target location.

func ReuseListenControl

func ReuseListenControl(_, _ string, c syscall.RawConn) error

ReuseListenControl can be used as Control field in net.ListenConfig, to reuse port when listening tcp or udp port. In *NIX, this function will enable SO_REUSEADDR flag and SO_REUSEPORT flag to current socket fd.

func SetGlobalTranslator

func SetGlobalTranslator(translator xvalidator.UtTranslator)

SetGlobalTranslator stores given xvalidator.UtTranslator to global, it can be got by using GetGlobalTranslator.

func SilentPrintRouteFunc

func SilentPrintRouteFunc(_, _, _ string, _ int)

SilentPrintRouteFunc is a global gin.DebugPrintRouteFunc, which do nothing for logging, means silent.

func TranslateBindingError

func TranslateBindingError(err error, options ...TranslateOption) (result map[string]string, need4xx bool)

TranslateBindingError translates given error and TranslateOption-s to a field-message map. Note that returned boolean value means whether given error can be regarded as an HTTP 4xx status code, means a user induced error.

func WrapPprof

func WrapPprof(router gin.IRouter)

WrapPprof registers several pprof routes from package `net/http/pprof` to gin router. For more, please visit https://github.com/DeanThompson/ginpprof.

func WrapPprofSilently

func WrapPprofSilently(router gin.IRouter)

WrapPprofSilently registers several pprof routes from package `net/http/pprof` to gin router without any debug logging.

func WrapSwagger

func WrapSwagger(router gin.IRouter, swaggerDocGetter func() []byte, swaggerOptions ...SwaggerOption)

WrapSwagger registers swagger related routes to gin router, the documentation page will be served in `index.html` or the root of given router. Visit https://github.com/swagger-api/swagger-ui/blob/v3.17.2/docs/usage/configuration.md for SwaggerOptions' details. Note: this function is not allowed to be used on gin.Engine directly or any other gin.GroupEngine which has empty relativePath.

Example:

func ReadSwaggerDoc() []byte {
	bs, _ := os.ReadFile("./api/spec.json")
	return bs
}
xgin.WrapSwagger(engine.Group("/v1/swagger"), ReadSwaggerDoc) // => /v1/swagger/index.html

func WrapSwaggerSilently

func WrapSwaggerSilently(router gin.IRouter, swaggerDocGetter func() []byte, swaggerOptions ...SwaggerOption)

WrapSwaggerSilently registers swagger related routes to gin router without any debug logging.

Types

type DebugPrintRouteFuncType

type DebugPrintRouteFuncType func(httpMethod, absolutePath, handlerName string, numHandlers int)

DebugPrintRouteFuncType represents the function type of gin.DebugPrintRouteFunc.

type DumpRequestOption

type DumpRequestOption func(*dumpRequestOptions)

DumpRequestOption represents an option type for DumpHttpRequest's option, can be created by WithXXX functions.

func WithIgnoreHeaders

func WithIgnoreHeaders(headers ...string) DumpRequestOption

WithIgnoreHeaders creates a DumpRequestOption for headers which are wanted to ignore, this option will be ignored when used with WithRetainHeaders.

func WithIgnoreRequestLine

func WithIgnoreRequestLine(ignore bool) DumpRequestOption

WithIgnoreRequestLine creates a DumpRequestOption for request line, if set to true, request line "GET /xxx HTTP/1.1" will be ignored.

func WithRetainHeaders

func WithRetainHeaders(headers ...string) DumpRequestOption

WithRetainHeaders creates a DumpRequestOption for headers which are wanted to retain, WithIgnoreHeaders option will be ignored when use with this.

func WithSecretHeaders

func WithSecretHeaders(headers ...string) DumpRequestOption

WithSecretHeaders creates a DumpRequestOption for headers which are secret, such as Authorization field, also see WithSecretPlaceholder.

func WithSecretPlaceholder

func WithSecretPlaceholder(placeholder string) DumpRequestOption

WithSecretPlaceholder creates a DumpRequestOption to specify a secret placeholder for secret headers set by WithSecretHeaders, defaults to "*".

type LoggerOption

type LoggerOption func(*loggerOptions)

LoggerOption represents an option type for some logger functions' option, can be created by WithXXX functions.

func WithExtraFields

func WithExtraFields(fields map[string]interface{}) LoggerOption

WithExtraFields creates a LoggerOption to specify logging with extra fields. Note that if you use this multiple times, only the last one will be retained.

func WithExtraFieldsV

func WithExtraFieldsV(fields ...interface{}) LoggerOption

WithExtraFieldsV creates a LoggerOption to specify logging with extra fields in variadic. Note that if you use this multiple times, only the last one will be retained.

func WithExtraText

func WithExtraText(text string) LoggerOption

WithExtraText creates a LoggerOption to specify extra text logging in "...extra_text" style. Note that if you use this multiple times, only the last one will be retained.

func WithMoreExtraFields

func WithMoreExtraFields(fields map[string]interface{}) LoggerOption

WithMoreExtraFields creates a LoggerOption to specify logging with extra fields. Note that if you use this multiple times, all previous contents will be retained.

func WithMoreExtraFieldsV

func WithMoreExtraFieldsV(fields ...interface{}) LoggerOption

WithMoreExtraFieldsV creates a LoggerOption to specify logging with extra fields in variadic. Note that if you use this multiple times, all previous contents will be retained.

func WithMoreExtraText

func WithMoreExtraText(text string) LoggerOption

WithMoreExtraText creates a LoggerOption to specify extra text logging in "...extra_text" style. Note that if you use this multiple times, all previous contents will be retained.

type NewEngineOption

type NewEngineOption func(o *newEngineOptions)

NewEngineOption represents an option type for NewEngine's option, can be created by WithXXX functions.

func WithContextWithFallback

func WithContextWithFallback(contextWithFallback bool) NewEngineOption

WithContextWithFallback creates a NewEngineOption to specify gin engine's contextWithFallback, defaults to false.

func WithDebugPrintRouteFunc

func WithDebugPrintRouteFunc(debugPrintRouteFunc DebugPrintRouteFuncType) NewEngineOption

WithDebugPrintRouteFunc creates a NewEngineOption to specify gin's global debugPrintRouteFunc, defaults to DefaultPrintRouteFunc.

func WithDefaultErrorWriter

func WithDefaultErrorWriter(defaultErrorWriter io.Writer) NewEngineOption

WithDefaultErrorWriter creates a NewEngineOption to specify gin's global defaultErrorWriter, defaults to os.Stderr.

func WithDefaultWriter

func WithDefaultWriter(defaultWriter io.Writer) NewEngineOption

WithDefaultWriter creates a NewEngineOption to specify gin's global defaultWriter, defaults to os.Stdout.

func WithForwardedByClientIP

func WithForwardedByClientIP(forwardedByClientIP bool) NewEngineOption

WithForwardedByClientIP creates a NewEngineOption to specify gin engine's forwardedByClientIP, defaults to true.

func WithHandleMethodNotAllowed

func WithHandleMethodNotAllowed(handleMethodNotAllowed bool) NewEngineOption

WithHandleMethodNotAllowed creates a NewEngineOption to specify gin engine's handleMethodNotAllowed, defaults to false.

func WithMaxMultipartMemory

func WithMaxMultipartMemory(maxMultipartMemory int64) NewEngineOption

WithMaxMultipartMemory creates a NewEngineOption to specify gin engine's maxMultipartMemory, defaults to 32 MB.

func WithMode

func WithMode(mode string) NewEngineOption

WithMode creates a NewEngineOption to specify gin's global mode, defaults to gin.DebugMode.

func WithNoMethod

func WithNoMethod(noMethod gin.HandlersChain) NewEngineOption

WithNoMethod creates a NewEngineOption to specify gin engine's noMethod, defaults to nil.

func WithNoRoute

func WithNoRoute(noRoute gin.HandlersChain) NewEngineOption

WithNoRoute creates a NewEngineOption to specify gin engine's noRoute, defaults to nil.

func WithRedirectFixedPath

func WithRedirectFixedPath(redirectFixedPath bool) NewEngineOption

WithRedirectFixedPath creates a NewEngineOption to specify gin engine's redirectFixedPath, defaults to false.

func WithRedirectTrailingSlash

func WithRedirectTrailingSlash(redirectTrailingSlash bool) NewEngineOption

WithRedirectTrailingSlash creates a NewEngineOption to specify gin engine's redirectTrailingSlash, defaults to true.

func WithRemoteIPHeaders

func WithRemoteIPHeaders(remoteIPHeaders []string) NewEngineOption

WithRemoteIPHeaders creates a NewEngineOption to specify gin engine's remoteIPHeaders, defaults to ["X-Forwarded-For", "X-Real-IP"].

func WithRemoveExtraSlash

func WithRemoveExtraSlash(removeExtraSlash bool) NewEngineOption

WithRemoveExtraSlash creates a NewEngineOption to specify gin engine's removeExtraSlash, defaults to false.

func WithSecureJSONPrefix

func WithSecureJSONPrefix(secureJSONPrefix string) NewEngineOption

WithSecureJSONPrefix creates a NewEngineOption to specify gin engine's secureJSONPrefix, defaults to "while(1);".

func WithTrustedPlatform

func WithTrustedPlatform(trustedPlatform string) NewEngineOption

WithTrustedPlatform creates a NewEngineOption to specify gin engine's trustedPlatform, defaults to "".

func WithTrustedProxies

func WithTrustedProxies(trustedProxies []string) NewEngineOption

WithTrustedProxies creates a NewEngineOption to specify gin engine's trustedProxies, defaults to ["0.0.0.0/0", "::/0"].

func WithUnescapePathValues

func WithUnescapePathValues(unescapePathValues bool) NewEngineOption

WithUnescapePathValues creates a NewEngineOption to specify gin engine's unescapePathValues, defaults to true.

func WithUseH2C

func WithUseH2C(useH2C bool) NewEngineOption

WithUseH2C creates a NewEngineOption to specify gin engine's useH2C, defaults to false.

func WithUseRawPath

func WithUseRawPath(useRawPath bool) NewEngineOption

WithUseRawPath creates a NewEngineOption to specify gin engine's useRawPath, defaults to false.

type RecoveryLoggerParam

type RecoveryLoggerParam struct {
	// origin
	PanicValue interface{}
	TraceStack xruntime.TraceStack

	// field
	PanicMsg     string
	FullFilename string
	FullFuncname string
	LineIndex    int
	LineText     string
}

RecoveryLoggerParam stores some logger parameters used by LogRecoveryToLogrus and LogRecoveryToLogger.

type ResponseLoggerParam

type ResponseLoggerParam struct {
	// origin
	Context *gin.Context
	Errors  []*gin.Error

	// field
	Method    string
	Path      string
	Query     string
	Status    int
	StartTime time.Time
	EndTime   time.Time
	Latency   time.Duration
	Length    int64
	ClientIP  string
	ErrorMsg  string
}

ResponseLoggerParam stores some logger parameters and is used by LogResponseToLogrus and LogResponseToLogger.

type RouterDecodeError

type RouterDecodeError struct {
	Field   string
	Input   string
	Err     error
	Message string
}

RouterDecodeError is an error type for router parameter decoding. At most of the time, the Err field is expected to be strconv.NumError type generated by strconv functions such as strconv.ParseInt and strconv.Atoi. This type also supports custom translation behavior in TranslateBindingError with WithXginRouterDecodeError.

func NewRouterDecodeError

func NewRouterDecodeError(field string, input string, err error, message string) *RouterDecodeError

NewRouterDecodeError creates a new RouterDecodeError by given arguments, panics when using nil error.

func (*RouterDecodeError) Error

func (r *RouterDecodeError) Error() string

Error returns the formatted error message from RouterDecodeError. Note that returned value does not contain custom message.

func (*RouterDecodeError) Unwrap

func (r *RouterDecodeError) Unwrap() error

Unwrap returns the wrapped error from RouterDecodeError.

type SwaggerOption

type SwaggerOption func(o *SwaggerOptions)

SwaggerOption represents an option type for WrapSwagger's option, can be created by WithXXX functions.

func WithSwaggerConfigJsonRouteName

func WithSwaggerConfigJsonRouteName(configJsonRouteName string) SwaggerOption

WithSwaggerConfigJsonRouteName creates a SwaggerOption to specify swagger config.json route name, defaults to "config.json".

func WithSwaggerDeepLinking

func WithSwaggerDeepLinking(deepLinking bool) SwaggerOption

WithSwaggerDeepLinking creates a SwaggerOption to specify swagger deepLinking, defaults to true.

func WithSwaggerDefaultModelExpandDepth

func WithSwaggerDefaultModelExpandDepth(defaultModelExpandDepth int) SwaggerOption

WithSwaggerDefaultModelExpandDepth creates a SwaggerOption to specify swagger defaultModelExpandDepth, defaults to 1.

func WithSwaggerDefaultModelRendering

func WithSwaggerDefaultModelRendering(defaultModelRendering string) SwaggerOption

WithSwaggerDefaultModelRendering creates a SwaggerOption to specify swagger defaultModelRendering, "example" and "model" are valid, defaults to "example".

func WithSwaggerDefaultModelsExpandDepth

func WithSwaggerDefaultModelsExpandDepth(defaultModelsExpandDepth int) SwaggerOption

WithSwaggerDefaultModelsExpandDepth creates a SwaggerOption to specify swagger defaultModelsExpandDepth, set to -1 completely hide the models, defaults to 1.

func WithSwaggerDisplayOperationId

func WithSwaggerDisplayOperationId(displayOperationId bool) SwaggerOption

WithSwaggerDisplayOperationId creates a SwaggerOption to specify swagger displayOperationId, defaults to false.

func WithSwaggerDisplayRequestDuration

func WithSwaggerDisplayRequestDuration(displayRequestDuration bool) SwaggerOption

WithSwaggerDisplayRequestDuration creates a SwaggerOption to specify swagger displayRequestDuration, defaults to false.

func WithSwaggerDocExpansion

func WithSwaggerDocExpansion(docExpansion string) SwaggerOption

WithSwaggerDocExpansion creates a SwaggerOption to specify swagger docExpansion, "list" and "full" and "none" are valid, defaults to "list".

func WithSwaggerDocJsonRouteName

func WithSwaggerDocJsonRouteName(docJsonRouteName string) SwaggerOption

WithSwaggerDocJsonRouteName creates a SwaggerOption to specify swagger doc.json route name, defaults to "doc.json".

func WithSwaggerEnableRedirect

func WithSwaggerEnableRedirect(enableRedirect bool) SwaggerOption

WithSwaggerEnableRedirect creates a SwaggerOption to specify whether to enable redirect route, defaults to true.

func WithSwaggerIndexHtmlRouteName

func WithSwaggerIndexHtmlRouteName(indexHtmlRouteName string) SwaggerOption

WithSwaggerIndexHtmlRouteName creates a SwaggerOption to specify swagger index.html route name, defaults to "index.html".

func WithSwaggerMaxDisplayedTags

func WithSwaggerMaxDisplayedTags(maxDisplayedTags int) SwaggerOption

WithSwaggerMaxDisplayedTags creates a SwaggerOption to specify swagger maxDisplayedTags, defaults to show all operations.

func WithSwaggerOperationsSorter

func WithSwaggerOperationsSorter(operationsSorter string) SwaggerOption

WithSwaggerOperationsSorter creates a SwaggerOption to specify swagger operationsSorter, "" and "alpha" and "method" are valid, defaults to "" which means not to sort.

func WithSwaggerShowCommonExtensions

func WithSwaggerShowCommonExtensions(showCommonExtensions bool) SwaggerOption

WithSwaggerShowCommonExtensions creates a SwaggerOption to specify swagger showCommonExtensions (pattern, maxLength, minLength, maximum, minimum), defaults to false.

func WithSwaggerShowExtensions

func WithSwaggerShowExtensions(showExtensions bool) SwaggerOption

WithSwaggerShowExtensions creates a SwaggerOption to specify swagger showExtensions, defaults to false.

func WithSwaggerTagsSorter

func WithSwaggerTagsSorter(tagsSorter string) SwaggerOption

WithSwaggerTagsSorter creates a SwaggerOption to specify swagger tagsSorter, "" and "alpha" is valid, default to "" which means not to sort.

type SwaggerOptions

type SwaggerOptions struct {
	IndexHtmlRouteName  string `json:"-"`
	DocJsonRouteName    string `json:"-"`
	ConfigJsonRouteName string `json:"-"`
	EnableRedirect      *bool  `json:"-"`

	DeepLinking              *bool   `json:"deepLinking,omitempty"`
	DisplayOperationId       *bool   `json:"displayOperationId,omitempty"`
	DefaultModelsExpandDepth *int    `json:"defaultModelsExpandDepth,omitempty"`
	DefaultModelExpandDepth  *int    `json:"defaultModelExpandDepth,omitempty"`
	DefaultModelRendering    *string `json:"defaultModelRendering,omitempty"`
	DisplayRequestDuration   *bool   `json:"displayRequestDuration,omitempty"`
	DocExpansion             *string `json:"docExpansion,omitempty"`
	MaxDisplayedTags         *int    `json:"maxDisplayedTags,omitempty"`
	OperationsSorter         *string `json:"operationsSorter,omitempty"`
	ShowExtensions           *bool   `json:"showExtensions,omitempty"`
	ShowCommonExtensions     *bool   `json:"showCommonExtensions,omitempty"`
	TagsSorter               *string `json:"tagsSorter,omitempty"`
}

SwaggerOptions is a type of WrapSwagger's option, each field can be set by SwaggerOption function type.

type TranslatableError

type TranslatableError interface {
	Error() string
	Translate() (result map[string]string, need4xx bool)
}

TranslatableError is an interface contains Translate method used in TranslateBindingError, can be used to specify the translation result of your error type.

type TranslateOption

type TranslateOption func(*translateOptions)

TranslateOption represents an option for TranslateBindingError's options, can be created by WithXXX functions.

func WithExtraErrorsTranslate

func WithExtraErrorsTranslate(fn func(error) (result map[string]string, need4xx bool)) TranslateOption

WithExtraErrorsTranslate creates a TranslateOption to specify translation function for other errors.

func WithIoEOFError

func WithIoEOFError(fn func(error) (result map[string]string, need4xx bool)) TranslateOption

WithIoEOFError creates a TranslateOption to specify translation function for io.EOF and io.ErrUnexpectedEOF.

func WithJsonInvalidUnmarshalError

func WithJsonInvalidUnmarshalError(fn func(*json.InvalidUnmarshalError) (result map[string]string, need4xx bool)) TranslateOption

WithJsonInvalidUnmarshalError creates a TranslateOption to specify translation function for json.InvalidUnmarshalError.

func WithJsonSyntaxError

func WithJsonSyntaxError(fn func(*json.SyntaxError) (result map[string]string, need4xx bool)) TranslateOption

WithJsonSyntaxError creates a TranslateOption to specify translation function for json.SyntaxError.

func WithJsonUnmarshalTypeError

func WithJsonUnmarshalTypeError(fn func(*json.UnmarshalTypeError) (result map[string]string, need4xx bool)) TranslateOption

WithJsonUnmarshalTypeError creates a TranslateOption to specify translation function for json.UnmarshalTypeError.

func WithStrconvNumErrorError

func WithStrconvNumErrorError(fn func(*strconv.NumError) (result map[string]string, need4xx bool)) TranslateOption

WithStrconvNumErrorError creates a TranslateOption to specify translation function for strconv.NumError.

func WithTranslatableError

func WithTranslatableError(fn func(TranslatableError) (result map[string]string, need4xx bool)) TranslateOption

WithTranslatableError creates a TranslateOption to specify translation function for errors that implement xgin.TranslatableError interface.

func WithUtTranslator

func WithUtTranslator(translator xvalidator.UtTranslator) TranslateOption

WithUtTranslator creates a TranslateOption to specify xvalidator.UtTranslator as the translation of validator.ValidationErrors and xvalidator.MultiFieldsError.

func WithValidatorFieldsError

func WithValidatorFieldsError(fn func(validator.ValidationErrors, xvalidator.UtTranslator) (result map[string]string, need4xx bool)) TranslateOption

WithValidatorFieldsError creates a TranslateOption to specify translation function for validator.ValidationErrors.

func WithValidatorInvalidTypeError

func WithValidatorInvalidTypeError(fn func(*validator.InvalidValidationError) (result map[string]string, need4xx bool)) TranslateOption

WithValidatorInvalidTypeError creates a TranslateOption to specify translation function for validator.InvalidValidationError.

func WithXginRouterDecodeError

func WithXginRouterDecodeError(fn func(*RouterDecodeError) (result map[string]string, need4xx bool)) TranslateOption

WithXginRouterDecodeError creates a TranslateOption to specify translation function for xgin.RouterDecodeError.

func WithXvalidatorMultiFieldsError

func WithXvalidatorMultiFieldsError(fn func(*xvalidator.MultiFieldsError, xvalidator.UtTranslator) (result map[string]string, need4xx bool)) TranslateOption

WithXvalidatorMultiFieldsError creates a TranslateOption to specify translation function for xvalidator.MultiFieldsError.

Jump to

Keyboard shortcuts

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