xf

package module
v0.0.0-...-19458f8 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2022 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const FieldCreatedAt = "created_at"
View Source
const FieldID = "id"
View Source
const FieldIsDeleted = "is_deleted"
View Source
const FieldUpdatedAt = "updated_at"

Variables

View Source
var Logger *zap.Logger
View Source
var MaxLengthOfRequestDump = 4 * 1024
View Source
var SlowGinRequestLatencyThreshold = time.Second
View Source
var SlowSQLDuration = time.Millisecond * 100
View Source
var VerySlowSQLDuration = time.Second

Functions

func AddHeaderToGRPCRequest

func AddHeaderToGRPCRequest(context context.Context, kv ...string) context.Context

AddHeaderToGRPCRequest is an alias to metadata.AppendToOutgoingContext in case you don't know how to add header to GRPC request. Now you know, just call metadata.AppendToOutgoingContext.

func AggregateLookup

func AggregateLookup(from, localField, foreignField, as string, pipeline []bson.M) map[string]any

func Auth2JSONMap

func Auth2JSONMap(obj any) map[string]string

func AutoRecover

func AutoRecover(ctx *CTX, job func())

func AutoRecoverAsync

func AutoRecoverAsync(ctx *CTX, job func())

func AutoRecoverReturns

func AutoRecoverReturns[T any](ctx *CTX, job func() T) T

func BytesToString

func BytesToString(b []byte) string

BytesToString converts byte slice to string without a memory allocation. Export from github.com/gin-gonic/gin.

func ConfigLogger

func ConfigLogger(config zap.Config)

func ContextByAppendingTraceID

func ContextByAppendingTraceID(context context.Context, traceID string) context.Context

func CreateDSNWith

func CreateDSNWith(driver, hostname string, port int32, user, password string) string

func Debug

func Debug(args ...interface{})

func Debugf

func Debugf(template string, args ...interface{})

func DefaultCollation

func DefaultCollation() *options.Collation

func Deleted

func Deleted() *int8

func DisableConsoleColor

func DisableConsoleColor()

DisableConsoleColor disables color output in the console.

func ErrModNoNeedToLog

func ErrModNoNeedToLog(et ErrorTypeWriteable)

func ErrModPrintAsInfo

func ErrModPrintAsInfo(et ErrorTypeWriteable)

func Error

func Error(args ...interface{})

func ErrorLogger

func ErrorLogger() gin.HandlerFunc

ErrorLogger returns a handlerfunc for any error type.

func ErrorLoggerT

func ErrorLoggerT(typ gin.ErrorType) gin.HandlerFunc

ErrorLoggerT returns a handlerfunc for a given error type.

func Errorf

func Errorf(template string, args ...interface{})

func Fatal

func Fatal(args ...interface{})

func Fatalf

func Fatalf(template string, args ...interface{})

func FileWithLineNumber

func FileWithLineNumber(index int) string

func FileWithLineNumberAfter

func FileWithLineNumberAfter(theFile string) string

FileWithLineNumberAfter return the file name and line number of the file after input theFile.

func ForceConsoleColor

func ForceConsoleColor()

ForceConsoleColor force color output in the console.

func GRPCClientZapLogOption

func GRPCClientZapLogOption() grpc_zap.Option

GRPCClientZapLogOption almost the same compare to grpc_zap.DefaultMessageProducer. Additionally, log traceID.

func GRPCServerZapLogOption

func GRPCServerZapLogOption() grpc_zap.Option

GRPCServerZapLogOption almost the same compare to grpc_zap.DefaultMessageProducer. Additionally, log traceID.

func GetJWTClaims

func GetJWTClaims(c *gin.Context, claimsPointer any)

func GetJWTMapClaims

func GetJWTMapClaims(c *gin.Context) map[string]any

func GetSliceInMap

func GetSliceInMap(paraName string, m map[string]any) ([]any, bool)

func GetStringInMap

func GetStringInMap(paraName string, m map[string]any) (string, bool)

func GinLogger

func GinLogger() gin.HandlerFunc

GinLogger instances a Logger middleware that will write the logs to gin.DefaultWriter. By default gin.DefaultWriter = os.Stdout.

func GinMiddleware

func GinMiddleware() gin.HandlerFunc

func HandlePost

func HandlePost(group *gin.RouterGroup, relativePath string, handlers ...HandlerFunc)

func IndexCreatedAt

func IndexCreatedAt() mongo.IndexModel

func IndexID

func IndexID() mongo.IndexModel

func IndexIsDeleted

func IndexIsDeleted() mongo.IndexModel

func IndexUpdatedAt

func IndexUpdatedAt() mongo.IndexModel

func Info

func Info(args ...interface{})

func Infof

func Infof(template string, args ...interface{})

func IsValueNil

func IsValueNil(i interface{}) bool

func LimitModFields

func LimitModFields(modFields map[string]struct{}, updates map[string]any)

LimitModFields 将不允许修改的字段剔除

func LogLevelOfString

func LogLevelOfString(str string) zapcore.Level

func LoggerWithConfig

func LoggerWithConfig(conf LoggerConfig) gin.HandlerFunc

LoggerWithConfig instance a Logger middleware with config.

func LoggerWithFormatter

func LoggerWithFormatter(f LogFormatter) gin.HandlerFunc

LoggerWithFormatter instance a Logger middleware with the specified log format function.

func LoggerWithWriter

func LoggerWithWriter(out io.Writer, notlogged ...string) gin.HandlerFunc

LoggerWithWriter instance a Logger middleware with the specified writer buffer. Example: os.Stdout, a file opened in write mode, a socket...

func MapFields

func MapFields[T any](m map[string]any, method MapFieldsMethod)

MapFields 把json字段名改成bson或gorm字段名。

func MapSliceToBSONA

func MapSliceToBSONA(input []map[string]any) bson.A

func MapToType

func MapToType(m map[string]interface{}, t interface{})

func MongoCollectionMustExist

func MongoCollectionMustExist(mongoDB *mongo.Database, name string) bool

MongoCollectionMustExist return true if collection exists.

func MustFixFilter

func MustFixFilter(filter map[string]any)

func MustGetSliceInMap

func MustGetSliceInMap(paraName string, m map[string]any) []any

func MustGetStringInMap

func MustGetStringInMap(paraName string, m map[string]any) string

func MustQueryRow

func MustQueryRow(db *sqlx.DB, query string, args ...interface{}) map[string]interface{}

func MustSetupMongoCollection

func MustSetupMongoCollection(mongoDB *mongo.Database, name string, validator bson.M, indexes []mongo.IndexModel)

MustSetupMongoCollection creates collection if not exists.

func MustValidateMap

func MustValidateMap[T any](m map[string]interface{})

MustValidateMap 检查map里的键值类型,是否符合T类型中相同参数名的类型。 map中缺少的参数,或增加的参数,无法被验证。

func NotDeleted

func NotDeleted() int8

func OverwrittenByJWT

func OverwrittenByJWT(c *gin.Context, mapping map[string]string, json map[string]any)

func Panic

func Panic(args ...interface{})

func Panicf

func Panicf(template string, args ...interface{})

func ParseXFTag

func ParseXFTag(obj any, dbTag string) (
	filterFields map[string][]string,
	searchableFields []string,
	listFields, detailFields map[string]any,
	modFields map[string]struct{},
)

func ReloadLogger

func ReloadLogger(custom func(config *zap.Config))

func SQLTrace

func SQLTrace(traceID, file string, begin time.Time, sql string, args ...interface{})

func SecureSQLName

func SecureSQLName(name string) string

SecureSQLName 过滤表/库/字段名,防止SQL注入

func SetLogLevel

func SetLogLevel(level zapcore.Level)

func ShortUUID

func ShortUUID(length int) string

ShortUUID returns a certain length of UUID string. length must between [1, 32]. There is no '-' in returned uuid. Will panic if length is not in the range.

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes converts string to byte slice without a memory allocation. Export from github.com/gin-gonic/gin.

func TraceIDFromIncoming

func TraceIDFromIncoming(context context.Context) string

TraceIDFromIncoming extract tid from context. return "" if not found.

func TraceIDFromMD

func TraceIDFromMD(md metadata.MD) string

func TraceIDFromOutgoing

func TraceIDFromOutgoing(context context.Context) string

TraceIDFromOutgoing extract tid from context. return "" if not found.

func UUID12

func UUID12() string

UUID12 returns a length of 12 characters UUID string.

func UUID4

func UUID4() string

UUID4 returns a length of 4 characters UUID string.

func UUID8

func UUID8() string

UUID8 returns a length of 8 characters UUID string.

func UniqueIndexOption

func UniqueIndexOption() *options.IndexOptions

func Warn

func Warn(args ...interface{})

func Warnf

func Warnf(template string, args ...interface{})

Types

type API

type API[T any] struct {
	Dir        string
	ItemName   string
	ListName   string
	GLASUD     string // 默认开放的接口
	Pagination bool   // 列表接口是否分页

	Auth2JSON map[string]string

	PageGetter  func(h *GinHelper, req *PageMeta) []*T
	ListGetter  func(h *GinHelper, req *PageMeta) []*T
	CountGetter func(h *GinHelper, req *PageMeta) int64
	Adder       func(h *GinHelper, req *T) (id any)
	Saver       func(h *GinHelper, req *T)
	Deleter     func(h *GinHelper, filter map[string]any)
	Setter      func(h *GinHelper, updates map[string]any)
	Getter      func(h *GinHelper, filter map[string]any) *T
}

func (*API[T]) MustGetJSONReq

func (r *API[T]) MustGetJSONReq(h *GinHelper) map[string]interface{}

func (*API[T]) MustGetObjReq

func (r *API[T]) MustGetObjReq(h *GinHelper, reqPtr any)

func (*API[T]) MustGetPageReq

func (r *API[T]) MustGetPageReq(h *GinHelper) *PageMeta

func (*API[T]) RegisterAPI

func (r *API[T]) RegisterAPI(parent *gin.RouterGroup) (group *gin.RouterGroup)

type AggregateParameters

type AggregateParameters struct {
	Page         *PageMeta
	Fields       map[string]any
	Lookups      []map[string]any
	BeforeLookup bson.A
	AfterLookup  bson.A
}

type CTX

type CTX struct {

	// Sometimes developer feels difficult to choose between panic and return-error.
	// In this case, try using PoR or PoRErr.
	// PreferPanic is a preference to PoR and PoRErr.
	PreferPanic bool
	// contains filtered or unexported fields
}

CTX is short for Context. Name is different from context.Context or gin.Context for preventing confusion.

func NewCTXWithGRPCContext

func NewCTXWithGRPCContext(context context.Context) *CTX

func NewCTXWithTraceID

func NewCTXWithTraceID(traceID string) *CTX

func NewContext

func NewContext() *CTX

func (*CTX) CreateGRPCContext

func (c *CTX) CreateGRPCContext() context.Context

CreateGRPCContext create a context.Context with header "tid".

func (*CTX) FillGRPCContext

func (c *CTX) FillGRPCContext(context context.Context) context.Context

FillGRPCContext append "tid" to context.Context .

func (*CTX) Get

func (c *CTX) Get(key string) interface{}

Get returns the value for the given key. If the value does not exist it returns nil.

func (*CTX) PoR

func (c *CTX) PoR(et ErrorType) ErrorType

PoR Panic or return the error referred by PreferPanic.

func (*CTX) PoRErr

func (c *CTX) PoRErr(err error) error

PoRErr Panic or return the error referred by PreferPanic.

func (*CTX) Set

func (c *CTX) Set(key string, value interface{})

Set is used to store a new key/value pair exclusively for this context.

func (*CTX) TraceID

func (c *CTX) TraceID() string

TraceID returns TraceID. Create one if not.

type CommonFields

type CommonFields struct {
	ID        any        `json:"id,omitempty" form:"id" bson:"id" gorm:"primaryKey" xf:"filter,omit:mod"`
	CreatedAt *time.Time `` /* 159-byte string literal not displayed */
	UpdatedAt *time.Time `` /* 144-byte string literal not displayed */
	IsDeleted *int8      `` /* 184-byte string literal not displayed */
}

func (*CommonFields) GetCreatedAt

func (r *CommonFields) GetCreatedAt() *time.Time

func (*CommonFields) GetID

func (r *CommonFields) GetID() any

func (*CommonFields) GetIsDeleted

func (r *CommonFields) GetIsDeleted() bool

func (*CommonFields) GetUpdatedAt

func (r *CommonFields) GetUpdatedAt() *time.Time

func (*CommonFields) SetCreatedAt

func (r *CommonFields) SetCreatedAt(t *time.Time)

func (*CommonFields) SetID

func (r *CommonFields) SetID(id any)

func (*CommonFields) SetIsDeleted

func (r *CommonFields) SetIsDeleted(d bool)

func (*CommonFields) SetUpdatedAt

func (r *CommonFields) SetUpdatedAt(t *time.Time)

type CommonModel

type CommonModel[T any] interface {
	ID
	GetCreatedAt() *time.Time
	SetCreatedAt(*time.Time)
	GetUpdatedAt() *time.Time
	SetUpdatedAt(*time.Time)
	GetIsDeleted() bool
	SetIsDeleted(bool)
}

type CommonSvc

type CommonSvc[T any, P CommonModel[T]] struct {
	*CTX
	GenericDAO func(*CTX) DAO[T, P]
	// 查询列表数据,返回的每个对象包含的字段,不填返回全部。值为1表示需要,值为0表示不需要。
	ListFields map[string]any
	// 查询详情数据包含的字段,不填返回全部。值为1表示需要,值为0表示不需要。
	DetailFields map[string]any
	// 查删改记录必填的查询字段,可以有多组,组名自定义,至少有一组中的所有参数必须全部命中。查询参数可以比必填参数多。
	FilterFields map[string][]string
	// 允许外部修改的字段,不在其中的将被剔除。
	//todo 不适用于增加记录
	ModFields map[string]struct{}
	// 通过关键字搜索时,要查哪些字段名。
	KeywordToFields []string
	// 通用代码不会查询这些字段
	HiddenFields []string
	// false,标记删除;true,物理删除;
	HardDeletion bool
	// 是否允许修改或删除多个记录。
	AllowsModMany bool
}

func (*CommonSvc[T, P]) FixPageForResponse

func (r *CommonSvc[T, P]) FixPageForResponse(page *PageMeta)

func (*CommonSvc[T, P]) MustAdd

func (r *CommonSvc[T, P]) MustAdd(doc P)

func (*CommonSvc[T, P]) MustCount

func (r *CommonSvc[T, P]) MustCount(page *PageMeta) int64

func (*CommonSvc[T, P]) MustDelete

func (r *CommonSvc[T, P]) MustDelete(filter map[string]any)

func (*CommonSvc[T, P]) MustGet

func (r *CommonSvc[T, P]) MustGet(filter map[string]any) P

func (*CommonSvc[T, P]) MustGetList

func (r *CommonSvc[T, P]) MustGetList(page *PageMeta) []P

func (*CommonSvc[T, P]) MustGetPage

func (r *CommonSvc[T, P]) MustGetPage(page *PageMeta) []P

func (*CommonSvc[T, P]) MustSave

func (r *CommonSvc[T, P]) MustSave(doc P)

func (*CommonSvc[T, P]) MustUpdate

func (r *CommonSvc[T, P]) MustUpdate(updates map[string]any) int64

func (*CommonSvc[T, P]) PrepareAdd

func (r *CommonSvc[T, P]) PrepareAdd(doc P)

func (*CommonSvc[T, P]) PrepareDelete

func (r *CommonSvc[T, P]) PrepareDelete(filter map[string]any)

func (*CommonSvc[T, P]) PrepareGet

func (r *CommonSvc[T, P]) PrepareGet(filter map[string]any)

func (*CommonSvc[T, P]) PreparePageRequest

func (r *CommonSvc[T, P]) PreparePageRequest(page *PageMeta)

func (*CommonSvc[T, P]) PrepareSave

func (r *CommonSvc[T, P]) PrepareSave(doc P)

func (*CommonSvc[T, P]) PrepareUpdates

func (r *CommonSvc[T, P]) PrepareUpdates(updates map[string]any) (filter map[string]any)

type DAO

type DAO[T any, P CommonModel[T]] interface {
	MustGetList(page *PageMeta, fields map[string]any) []P
	MustGetPage(page *PageMeta, fields map[string]any) []P
	MustCount(page *PageMeta) int64
	MustGet(filter, fields map[string]any) P
	Exist(filter map[string]any) bool
	MustAdd(doc P)
	MustUpdate(filter, updates map[string]any, advancedUpdates any) int64 // restrict to update one record
	MustUpdateMany(filter, updates map[string]any, advancedUpdates any) int64
	MustSave(doc P)
	MustSoftDelete(filter map[string]any) int64
	MustSoftDeleteMany(filter map[string]any) int64
	MustHardDelete(filter map[string]any) int64
	MustHardDeleteMany(filter map[string]any) int64
}

type DBXWithLogger

type DBXWithLogger struct {
	*sqlx.DB
	// contains filtered or unexported fields
}

func NewDBXWithLogger

func NewDBXWithLogger(dbx *sqlx.DB, traceID string, file string) *DBXWithLogger

func (*DBXWithLogger) Exec

func (o *DBXWithLogger) Exec(query string, args ...interface{}) (sql.Result, error)

func (*DBXWithLogger) Query

func (o *DBXWithLogger) Query(query string, args ...interface{}) (*sql.Rows, error)

func (*DBXWithLogger) QueryRowx

func (o *DBXWithLogger) QueryRowx(query string, args ...interface{}) *sqlx.Row

func (*DBXWithLogger) Queryx

func (o *DBXWithLogger) Queryx(query string, args ...interface{}) (*sqlx.Rows, error)

type ErrorPayload

type ErrorPayload struct {
	Code interface{} `json:"code,omitempty"`
	Desc string      `json:"desc"`
	TID  string      `json:"tid,omitempty"`
}

type ErrorType

type ErrorType interface {
	error
	ErrorCode() interface{}
	StatusCode() int
	Extra() interface{}
}

func DialGRPC

func DialGRPC(host string, panicIfErrorOccurred bool) (*grpc.ClientConn, ErrorType)

func ErrAnyError

func ErrAnyError(err any) ErrorType

func ErrDBQueryError

func ErrDBQueryError(query string, err any) ErrorType

func ErrForbidden

func ErrForbidden(err any) ErrorType

func ErrGRPCDialError

func ErrGRPCDialError(host string, err any) ErrorType

func ErrGeneralError

func ErrGeneralError(err any) ErrorType

func ErrInvalidJWTPayload

func ErrInvalidJWTPayload(err any) ErrorType

func ErrInvalidParameters

func ErrInvalidParameters(para string) ErrorType

func ErrMarshalJSONError

func ErrMarshalJSONError(err any) ErrorType

func ErrMongoConnectionError

func ErrMongoConnectionError(err any) ErrorType

func ErrMongoQueryError

func ErrMongoQueryError(err any) ErrorType

func ErrMongoTransactionError

func ErrMongoTransactionError(err any) ErrorType

func ErrMongoWriteError

func ErrMongoWriteError(err any) ErrorType

func ErrNotFound

func ErrNotFound(err any) ErrorType

func ErrParamBindingError

func ErrParamBindingError(err any) ErrorType

func ErrReadRequestBodyError

func ErrReadRequestBodyError(err any) ErrorType

func ErrServerInternalError

func ErrServerInternalError(err any) ErrorType

func ErrUnmarshalJSONError

func ErrUnmarshalJSONError(err any) ErrorType

func NewErrorType

func NewErrorType(errCode any, statusCode int, err any, a ...any) ErrorType

func TryConvertToErrorType

func TryConvertToErrorType(err interface{}) ErrorType

TryConvertToErrorType returns an ErrorType if err is an ErrorType. returns nil if not.

type ErrorTypeEntity

type ErrorTypeEntity struct {
	// contains filtered or unexported fields
}

func (ErrorTypeEntity) Error

func (e ErrorTypeEntity) Error() string

Error implementation to error interface.

func (ErrorTypeEntity) ErrorCode

func (e ErrorTypeEntity) ErrorCode() interface{}

ErrorCode change it as you prefer.

func (ErrorTypeEntity) Extra

func (e ErrorTypeEntity) Extra() interface{}

Extra returns _extra_ which can be set by user. Usage of _extra_ is determined by user.

func (ErrorTypeEntity) OriginalError

func (e ErrorTypeEntity) OriginalError() any

OriginalError returns original error if there is any.

func (*ErrorTypeEntity) SetExtra

func (e *ErrorTypeEntity) SetExtra(extra interface{})

SetExtra sets _extra_ with a value by user. Usage of _extra_ is determined by user.

func (ErrorTypeEntity) StatusCode

func (e ErrorTypeEntity) StatusCode() int

StatusCode refers to http response status code. Developer may want to set response status code based on error. For example, if the error is caused by bad request, then change the return value to 400. Ignore this function if no need for your project.

type ErrorTypeWriteable

type ErrorTypeWriteable interface {
	SetExtra(interface{})
}

type GinHelper

type GinHelper struct {
	*gin.Context
}

GinHelper provides some helper functions. Respond JSON only.

func NewGinHelper

func NewGinHelper(c *gin.Context) *GinHelper

func (*GinHelper) Bind

func (r *GinHelper) Bind(obj interface{}) bool

Bind Deprecated. binds parameters to obj which must be a pointer. If any error occurred, respond 400. return true if binding succeed, vice versa.

func (*GinHelper) BodyAsJSONSlice

func (r *GinHelper) BodyAsJSONSlice() (s []map[string]interface{}, et ErrorType)

func (*GinHelper) CTX

func (r *GinHelper) CTX() *CTX

func (*GinHelper) CreateGRPCContext

func (r *GinHelper) CreateGRPCContext() context.Context

CreateGRPCContext create a context.Context with header "tid".

func (*GinHelper) MustBind

func (r *GinHelper) MustBind(obj interface{})

MustBind binds parameters to obj which must be a pointer. If any error occurred, respond 400.

func (*GinHelper) Respond

func (r *GinHelper) Respond(status int, payload KV)

Respond Example: payload 1 is {k: "msg" v: "ok"}; payload 2 is {k: "data" v:{id: 1}}. Response JSON will be

{
	"error": null,
	"msg": "ok",
	"data": {
		"id": 1
	}
}

func (*GinHelper) RespondError

func (r *GinHelper) RespondError(et ErrorType)

RespondError responds error in a response in JSON format.

func (*GinHelper) RespondErrorElse

func (r *GinHelper) RespondErrorElse(successStatusCode int, et ErrorType)

RespondErrorElse if error is not nil, respond error.StatusCode() and error in the response JSON; Otherwise, respond successStatusCode and error: null in the response JSON

func (*GinHelper) RespondErrorElse200

func (r *GinHelper) RespondErrorElse200(et ErrorType)

func (*GinHelper) RespondFirst

func (r *GinHelper) RespondFirst(successStatusCode int, key string, values interface{}, et ErrorType)

RespondFirst caller provide an slice/array. Only the first element if exists will be in the response JSON. todo generic

func (*GinHelper) RespondFirst200

func (r *GinHelper) RespondFirst200(key string, values interface{}, et ErrorType)

func (*GinHelper) RespondKV

func (r *GinHelper) RespondKV(successStatusCode int, key string, value interface{}, et ErrorType)

RespondKV caller provides one object/array/slice and error, nil if no error. Function will make response properly.

func (*GinHelper) RespondKV200

func (r *GinHelper) RespondKV200(key string, value interface{}, et ErrorType)

func (*GinHelper) RespondKVs

func (r *GinHelper) RespondKVs(successStatusCode int, et ErrorType, payload KV)

RespondKVs caller provides multiple KV objects and error, nil if no error. Function will make response properly.

func (*GinHelper) RespondKVs200

func (r *GinHelper) RespondKVs200(et ErrorType, payload KV)

func (*GinHelper) UnmarshalJSONToMap

func (r *GinHelper) UnmarshalJSONToMap() (m map[string]interface{}, et ErrorType)

type HandlerFunc

type HandlerFunc func(helper *GinHelper)

type ID

type ID interface {
	GetID() any
	SetID(any)
}

type KV

type KV = map[string]interface{}

type LogFormatter

type LogFormatter func(params LogFormatterParams) string

LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter

type LogFormatterParams

type LogFormatterParams struct {
	Request *http.Request

	// TimeStamp shows the time after the server returns a response.
	TimeStamp time.Time
	// StatusCode is HTTP response code.
	StatusCode int
	// Latency is how much time the server cost to process a certain request.
	Latency time.Duration
	// ClientIP equals context's ClientIP method.
	ClientIP string
	// Method is the HTTP method given to the request.
	Method string
	// Path is a path the client requests.
	Path string
	// ErrorMessage is set if error has occurred in processing the request.
	ErrorMessage string

	// BodySize is the size of the Response Body
	BodySize int
	// Keys are the keys set on the request's context.
	Keys map[string]interface{}
	// contains filtered or unexported fields
}

LogFormatterParams is the structure any formatter will be handed when time to log comes

func (*LogFormatterParams) IsOutputColor

func (p *LogFormatterParams) IsOutputColor() bool

IsOutputColor indicates whether can colors be outputted to the log.

func (*LogFormatterParams) MethodColor

func (p *LogFormatterParams) MethodColor() string

MethodColor is the ANSI color for appropriately logging http method to a terminal.

func (*LogFormatterParams) ResetColor

func (p *LogFormatterParams) ResetColor() string

ResetColor resets all escape attributes.

func (*LogFormatterParams) StatusCodeColor

func (p *LogFormatterParams) StatusCodeColor() string

StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.

type LoggerConfig

type LoggerConfig struct {
	// Optional. Default value is gin.defaultLogFormatter
	Formatter LogFormatter

	// Output is a writer where logs are written.
	// Optional. Default value is gin.DefaultWriter.
	Output io.Writer

	// SkipPaths is an url path array which logs are not written.
	// Optional.
	SkipPaths []string
}

LoggerConfig defines the config for Logger middleware.

type MapFieldsMethod

type MapFieldsMethod string

MapFieldsMethod for caching purpose

const (
	MapFieldsMethodJsonToBson MapFieldsMethod = "JsonToBson"
	MapFieldsMethodJsonToGorm MapFieldsMethod = "JsonToGorm"
)

type MongoDAO

type MongoDAO[T any, P CommonModel[T]] struct {
	*CTX
	// contains filtered or unexported fields
}

func NewMongoDAO

func NewMongoDAO[T any, P CommonModel[T]](ctx *CTX, client *mongo.Client, collection *mongo.Collection) *MongoDAO[T, P]

func (*MongoDAO[T, P]) Exist

func (r *MongoDAO[T, P]) Exist(filter map[string]any) bool

func (*MongoDAO[T, P]) MustAdd

func (r *MongoDAO[T, P]) MustAdd(doc P)

func (*MongoDAO[T, P]) MustAddJSON

func (r *MongoDAO[T, P]) MustAddJSON(json map[string]any) any

func (*MongoDAO[T, P]) MustAddMany

func (r *MongoDAO[T, P]) MustAddMany(docs []P)

func (*MongoDAO[T, P]) MustAggregate

func (r *MongoDAO[T, P]) MustAggregate(pipeline []bson.M, customDecoding bool) ([]P, *mongo.Cursor)

func (*MongoDAO[T, P]) MustCount

func (r *MongoDAO[T, P]) MustCount(page *PageMeta) int64

func (*MongoDAO[T, P]) MustDistinct

func (r *MongoDAO[T, P]) MustDistinct(field string, filter bson.M) []any

func (*MongoDAO[T, P]) MustGet

func (r *MongoDAO[T, P]) MustGet(filter, fields map[string]any) P

func (*MongoDAO[T, P]) MustGetByAggregate

func (r *MongoDAO[T, P]) MustGetByAggregate(paras *AggregateParameters, otherCommand ...any) []P

func (*MongoDAO[T, P]) MustGetByAggregate2

func (r *MongoDAO[T, P]) MustGetByAggregate2(paras *AggregateParameters, alterPipeline func(pipeline *bson.A), otherCommand ...any) []P

func (*MongoDAO[T, P]) MustGetCommonFields

func (r *MongoDAO[T, P]) MustGetCommonFields(id any) *CommonFields

func (*MongoDAO[T, P]) MustGetList

func (r *MongoDAO[T, P]) MustGetList(page *PageMeta, fields map[string]any) []P

func (*MongoDAO[T, P]) MustGetPage

func (r *MongoDAO[T, P]) MustGetPage(page *PageMeta, fields map[string]any) []P

func (*MongoDAO[T, P]) MustHardDelete

func (r *MongoDAO[T, P]) MustHardDelete(filter map[string]any) int64

func (*MongoDAO[T, P]) MustHardDeleteMany

func (r *MongoDAO[T, P]) MustHardDeleteMany(filter map[string]any) int64

func (*MongoDAO[T, P]) MustSave

func (r *MongoDAO[T, P]) MustSave(doc P)

func (*MongoDAO[T, P]) MustSoftDelete

func (r *MongoDAO[T, P]) MustSoftDelete(filter map[string]any) int64

func (*MongoDAO[T, P]) MustSoftDeleteMany

func (r *MongoDAO[T, P]) MustSoftDeleteMany(filter map[string]any) int64

func (*MongoDAO[T, P]) MustUpdate

func (r *MongoDAO[T, P]) MustUpdate(filter, updates map[string]any, advancedUpdates any) int64

func (*MongoDAO[T, P]) MustUpdateMany

func (r *MongoDAO[T, P]) MustUpdateMany(filter, updates map[string]any, advancedUpdates any) int64

func (*MongoDAO[T, P]) MustUpsert

func (r *MongoDAO[T, P]) MustUpsert(filter, updates map[string]any, advancedUpdates any) int64

func (*MongoDAO[T, P]) MustUpsertMany

func (r *MongoDAO[T, P]) MustUpsertMany(filter, updates map[string]any, advancedUpdates any) int64

func (*MongoDAO[T, P]) SessionContext

func (r *MongoDAO[T, P]) SessionContext() context.Context

func (*MongoDAO[T, P]) Transaction

func (r *MongoDAO[T, P]) Transaction(do func(session context.Context))

Transaction only available for replica set

func (*MongoDAO[T, P]) UseSession

func (r *MongoDAO[T, P]) UseSession(sessionContext context.Context)

type PageMeta

type PageMeta struct {
	// 从某个条件(一般是ID或日期)开始查询数据,和Page参数二选一
	Start any `json:"start,omitempty" form:"start" uri:"start" bson:"start"`

	// 页数,和Start参数二选一
	Page *int64 `json:"page,omitempty" form:"page" uri:"page" bson:"page"`

	// 一页的条数
	Size int64 `json:"size,omitempty" form:"size" uri:"size" bson:"size"`

	// 排序 {"field": -1} -1, desc; 1, asc;
	SortBy map[string]any `json:"sort_by,omitempty" form:"sort_by" bson:"sort_by"`

	// 匹配条件
	Match map[string]any `json:"match,omitempty" form:"match" bson:"match"`

	// 全文模糊搜索条件
	Search map[string]any `json:"search,omitempty" form:"search" bson:"search"`

	// 全文模糊搜索文本
	SearchText string `json:"search_text,omitempty" form:"search_text" bson:"search_text"`

	// 总共(约)有多少条记录。仅作为返回值。
	Total *int64 `json:"total,omitempty" form:"total" bson:"total"`
}

PageMeta 通用的分页请求参数模型

type PageResp

type PageResp[T any] struct {
	*PageMeta
	Data []*T `json:"data"`
}

type TXXWithLogger

type TXXWithLogger struct {
	*sqlx.Tx
	// contains filtered or unexported fields
}

func NewTXXWithLogger

func NewTXXWithLogger(txx *sqlx.Tx, traceID string, file string) *TXXWithLogger

func (*TXXWithLogger) Exec

func (o *TXXWithLogger) Exec(query string, args ...interface{}) (sql.Result, error)

func (*TXXWithLogger) Query

func (o *TXXWithLogger) Query(query string, args ...interface{}) (*sql.Rows, error)

func (*TXXWithLogger) QueryRowx

func (o *TXXWithLogger) QueryRowx(query string, args ...interface{}) *sqlx.Row

func (*TXXWithLogger) Queryx

func (o *TXXWithLogger) Queryx(query string, args ...interface{}) (*sqlx.Rows, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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