Documentation ¶
Index ¶
- Constants
- Variables
- func AddHeaderToGRPCRequest(context context.Context, kv ...string) context.Context
- func AggregateLookup(from, localField, foreignField, as string, pipeline []bson.M) map[string]any
- func Auth2JSONMap(obj any) map[string]string
- func AutoRecover(ctx *CTX, job func())
- func AutoRecoverAsync(ctx *CTX, job func())
- func AutoRecoverReturns[T any](ctx *CTX, job func() T) T
- func BytesToString(b []byte) string
- func ConfigLogger(config zap.Config)
- func ContextByAppendingTraceID(context context.Context, traceID string) context.Context
- func CreateDSNWith(driver, hostname string, port int32, user, password string) string
- func Debug(args ...interface{})
- func Debugf(template string, args ...interface{})
- func DefaultCollation() *options.Collation
- func Deleted() *int8
- func DisableConsoleColor()
- func ErrModNoNeedToLog(et ErrorTypeWriteable)
- func ErrModPrintAsInfo(et ErrorTypeWriteable)
- func Error(args ...interface{})
- func ErrorLogger() gin.HandlerFunc
- func ErrorLoggerT(typ gin.ErrorType) gin.HandlerFunc
- func Errorf(template string, args ...interface{})
- func Fatal(args ...interface{})
- func Fatalf(template string, args ...interface{})
- func FileWithLineNumber(index int) string
- func FileWithLineNumberAfter(theFile string) string
- func ForceConsoleColor()
- func GRPCClientZapLogOption() grpc_zap.Option
- func GRPCServerZapLogOption() grpc_zap.Option
- func GetJWTClaims(c *gin.Context, claimsPointer any)
- func GetJWTMapClaims(c *gin.Context) map[string]any
- func GetSliceInMap(paraName string, m map[string]any) ([]any, bool)
- func GetStringInMap(paraName string, m map[string]any) (string, bool)
- func GinLogger() gin.HandlerFunc
- func GinMiddleware() gin.HandlerFunc
- func HandlePost(group *gin.RouterGroup, relativePath string, handlers ...HandlerFunc)
- func IndexCreatedAt() mongo.IndexModel
- func IndexID() mongo.IndexModel
- func IndexIsDeleted() mongo.IndexModel
- func IndexUpdatedAt() mongo.IndexModel
- func Info(args ...interface{})
- func Infof(template string, args ...interface{})
- func IsValueNil(i interface{}) bool
- func LimitModFields(modFields map[string]struct{}, updates map[string]any)
- func LogLevelOfString(str string) zapcore.Level
- func LoggerWithConfig(conf LoggerConfig) gin.HandlerFunc
- func LoggerWithFormatter(f LogFormatter) gin.HandlerFunc
- func LoggerWithWriter(out io.Writer, notlogged ...string) gin.HandlerFunc
- func MapFields[T any](m map[string]any, method MapFieldsMethod)
- func MapSliceToBSONA(input []map[string]any) bson.A
- func MapToType(m map[string]interface{}, t interface{})
- func MongoCollectionMustExist(mongoDB *mongo.Database, name string) bool
- func MustFixFilter(filter map[string]any)
- func MustGetSliceInMap(paraName string, m map[string]any) []any
- func MustGetStringInMap(paraName string, m map[string]any) string
- func MustQueryRow(db *sqlx.DB, query string, args ...interface{}) map[string]interface{}
- func MustSetupMongoCollection(mongoDB *mongo.Database, name string, validator bson.M, ...)
- func MustValidateMap[T any](m map[string]interface{})
- func NotDeleted() int8
- func OverwrittenByJWT(c *gin.Context, mapping map[string]string, json map[string]any)
- func Panic(args ...interface{})
- func Panicf(template string, args ...interface{})
- func ParseXFTag(obj any, dbTag string) (filterFields map[string][]string, searchableFields []string, ...)
- func ReloadLogger(custom func(config *zap.Config))
- func SQLTrace(traceID, file string, begin time.Time, sql string, args ...interface{})
- func SecureSQLName(name string) string
- func SetLogLevel(level zapcore.Level)
- func ShortUUID(length int) string
- func StringToBytes(s string) []byte
- func TraceIDFromIncoming(context context.Context) string
- func TraceIDFromMD(md metadata.MD) string
- func TraceIDFromOutgoing(context context.Context) string
- func UUID12() string
- func UUID4() string
- func UUID8() string
- func UniqueIndexOption() *options.IndexOptions
- func Warn(args ...interface{})
- func Warnf(template string, args ...interface{})
- type API
- type AggregateParameters
- type CTX
- func (c *CTX) CreateGRPCContext() context.Context
- func (c *CTX) FillGRPCContext(context context.Context) context.Context
- func (c *CTX) Get(key string) interface{}
- func (c *CTX) PoR(et ErrorType) ErrorType
- func (c *CTX) PoRErr(err error) error
- func (c *CTX) Set(key string, value interface{})
- func (c *CTX) TraceID() string
- type CommonFields
- func (r *CommonFields) GetCreatedAt() *time.Time
- func (r *CommonFields) GetID() any
- func (r *CommonFields) GetIsDeleted() bool
- func (r *CommonFields) GetUpdatedAt() *time.Time
- func (r *CommonFields) SetCreatedAt(t *time.Time)
- func (r *CommonFields) SetID(id any)
- func (r *CommonFields) SetIsDeleted(d bool)
- func (r *CommonFields) SetUpdatedAt(t *time.Time)
- type CommonModel
- type CommonSvc
- func (r *CommonSvc[T, P]) FixPageForResponse(page *PageMeta)
- func (r *CommonSvc[T, P]) MustAdd(doc P)
- func (r *CommonSvc[T, P]) MustCount(page *PageMeta) int64
- func (r *CommonSvc[T, P]) MustDelete(filter map[string]any)
- func (r *CommonSvc[T, P]) MustGet(filter map[string]any) P
- func (r *CommonSvc[T, P]) MustGetList(page *PageMeta) []P
- func (r *CommonSvc[T, P]) MustGetPage(page *PageMeta) []P
- func (r *CommonSvc[T, P]) MustSave(doc P)
- func (r *CommonSvc[T, P]) MustUpdate(updates map[string]any) int64
- func (r *CommonSvc[T, P]) PrepareAdd(doc P)
- func (r *CommonSvc[T, P]) PrepareDelete(filter map[string]any)
- func (r *CommonSvc[T, P]) PrepareGet(filter map[string]any)
- func (r *CommonSvc[T, P]) PreparePageRequest(page *PageMeta)
- func (r *CommonSvc[T, P]) PrepareSave(doc P)
- func (r *CommonSvc[T, P]) PrepareUpdates(updates map[string]any) (filter map[string]any)
- type DAO
- type DBXWithLogger
- func (o *DBXWithLogger) Exec(query string, args ...interface{}) (sql.Result, error)
- func (o *DBXWithLogger) Query(query string, args ...interface{}) (*sql.Rows, error)
- func (o *DBXWithLogger) QueryRowx(query string, args ...interface{}) *sqlx.Row
- func (o *DBXWithLogger) Queryx(query string, args ...interface{}) (*sqlx.Rows, error)
- type ErrorPayload
- type ErrorType
- func DialGRPC(host string, panicIfErrorOccurred bool) (*grpc.ClientConn, ErrorType)
- func ErrAnyError(err any) ErrorType
- func ErrDBQueryError(query string, err any) ErrorType
- func ErrForbidden(err any) ErrorType
- func ErrGRPCDialError(host string, err any) ErrorType
- func ErrGeneralError(err any) ErrorType
- func ErrInvalidJWTPayload(err any) ErrorType
- func ErrInvalidParameters(para string) ErrorType
- func ErrMarshalJSONError(err any) ErrorType
- func ErrMongoConnectionError(err any) ErrorType
- func ErrMongoQueryError(err any) ErrorType
- func ErrMongoTransactionError(err any) ErrorType
- func ErrMongoWriteError(err any) ErrorType
- func ErrNotFound(err any) ErrorType
- func ErrParamBindingError(err any) ErrorType
- func ErrReadRequestBodyError(err any) ErrorType
- func ErrServerInternalError(err any) ErrorType
- func ErrUnmarshalJSONError(err any) ErrorType
- func NewErrorType(errCode any, statusCode int, err any, a ...any) ErrorType
- func TryConvertToErrorType(err interface{}) ErrorType
- type ErrorTypeEntity
- type ErrorTypeWriteable
- type GinHelper
- func (r *GinHelper) Bind(obj interface{}) bool
- func (r *GinHelper) BodyAsJSONSlice() (s []map[string]interface{}, et ErrorType)
- func (r *GinHelper) CTX() *CTX
- func (r *GinHelper) CreateGRPCContext() context.Context
- func (r *GinHelper) MustBind(obj interface{})
- func (r *GinHelper) Respond(status int, payload KV)
- func (r *GinHelper) RespondError(et ErrorType)
- func (r *GinHelper) RespondErrorElse(successStatusCode int, et ErrorType)
- func (r *GinHelper) RespondErrorElse200(et ErrorType)
- func (r *GinHelper) RespondFirst(successStatusCode int, key string, values interface{}, et ErrorType)
- func (r *GinHelper) RespondFirst200(key string, values interface{}, et ErrorType)
- func (r *GinHelper) RespondKV(successStatusCode int, key string, value interface{}, et ErrorType)
- func (r *GinHelper) RespondKV200(key string, value interface{}, et ErrorType)
- func (r *GinHelper) RespondKVs(successStatusCode int, et ErrorType, payload KV)
- func (r *GinHelper) RespondKVs200(et ErrorType, payload KV)
- func (r *GinHelper) UnmarshalJSONToMap() (m map[string]interface{}, et ErrorType)
- type HandlerFunc
- type ID
- type KV
- type LogFormatter
- type LogFormatterParams
- type LoggerConfig
- type MapFieldsMethod
- type MongoDAO
- func (r *MongoDAO[T, P]) Exist(filter map[string]any) bool
- func (r *MongoDAO[T, P]) MustAdd(doc P)
- func (r *MongoDAO[T, P]) MustAddJSON(json map[string]any) any
- func (r *MongoDAO[T, P]) MustAddMany(docs []P)
- func (r *MongoDAO[T, P]) MustAggregate(pipeline []bson.M, customDecoding bool) ([]P, *mongo.Cursor)
- func (r *MongoDAO[T, P]) MustCount(page *PageMeta) int64
- func (r *MongoDAO[T, P]) MustDistinct(field string, filter bson.M) []any
- func (r *MongoDAO[T, P]) MustGet(filter, fields map[string]any) P
- func (r *MongoDAO[T, P]) MustGetByAggregate(paras *AggregateParameters, otherCommand ...any) []P
- func (r *MongoDAO[T, P]) MustGetByAggregate2(paras *AggregateParameters, alterPipeline func(pipeline *bson.A), ...) []P
- func (r *MongoDAO[T, P]) MustGetCommonFields(id any) *CommonFields
- func (r *MongoDAO[T, P]) MustGetList(page *PageMeta, fields map[string]any) []P
- func (r *MongoDAO[T, P]) MustGetPage(page *PageMeta, fields map[string]any) []P
- func (r *MongoDAO[T, P]) MustHardDelete(filter map[string]any) int64
- func (r *MongoDAO[T, P]) MustHardDeleteMany(filter map[string]any) int64
- func (r *MongoDAO[T, P]) MustSave(doc P)
- func (r *MongoDAO[T, P]) MustSoftDelete(filter map[string]any) int64
- func (r *MongoDAO[T, P]) MustSoftDeleteMany(filter map[string]any) int64
- func (r *MongoDAO[T, P]) MustUpdate(filter, updates map[string]any, advancedUpdates any) int64
- func (r *MongoDAO[T, P]) MustUpdateMany(filter, updates map[string]any, advancedUpdates any) int64
- func (r *MongoDAO[T, P]) MustUpsert(filter, updates map[string]any, advancedUpdates any) int64
- func (r *MongoDAO[T, P]) MustUpsertMany(filter, updates map[string]any, advancedUpdates any) int64
- func (r *MongoDAO[T, P]) SessionContext() context.Context
- func (r *MongoDAO[T, P]) Transaction(do func(session context.Context))
- func (r *MongoDAO[T, P]) UseSession(sessionContext context.Context)
- type PageMeta
- type PageResp
- type TXXWithLogger
- func (o *TXXWithLogger) Exec(query string, args ...interface{}) (sql.Result, error)
- func (o *TXXWithLogger) Query(query string, args ...interface{}) (*sql.Rows, error)
- func (o *TXXWithLogger) QueryRowx(query string, args ...interface{}) *sqlx.Row
- func (o *TXXWithLogger) Queryx(query string, args ...interface{}) (*sqlx.Rows, error)
Constants ¶
const FieldCreatedAt = "created_at"
const FieldID = "id"
const FieldIsDeleted = "is_deleted"
const FieldUpdatedAt = "updated_at"
Variables ¶
var L *zap.SugaredLogger
var Logger *zap.Logger
var MaxLengthOfRequestDump = 4 * 1024
var SlowGinRequestLatencyThreshold = time.Second
var SlowSQLDuration = time.Millisecond * 100
var VerySlowSQLDuration = time.Second
Functions ¶
func AddHeaderToGRPCRequest ¶
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 Auth2JSONMap ¶
func AutoRecover ¶
func AutoRecover(ctx *CTX, job func())
func AutoRecoverAsync ¶
func AutoRecoverAsync(ctx *CTX, job func())
func AutoRecoverReturns ¶
func BytesToString ¶
BytesToString converts byte slice to string without a memory allocation. Export from github.com/gin-gonic/gin.
func ConfigLogger ¶
func CreateDSNWith ¶
func DefaultCollation ¶
func DisableConsoleColor ¶
func DisableConsoleColor()
DisableConsoleColor disables color output in the console.
func ErrModNoNeedToLog ¶
func ErrModNoNeedToLog(et ErrorTypeWriteable)
func ErrModPrintAsInfo ¶
func ErrModPrintAsInfo(et ErrorTypeWriteable)
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 FileWithLineNumber ¶
func FileWithLineNumberAfter ¶
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 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 IsValueNil ¶
func IsValueNil(i interface{}) bool
func LimitModFields ¶
LimitModFields 将不允许修改的字段剔除
func LogLevelOfString ¶
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 MongoCollectionMustExist ¶
MongoCollectionMustExist return true if collection exists.
func MustFixFilter ¶
func MustQueryRow ¶
func MustSetupMongoCollection ¶
func MustSetupMongoCollection(mongoDB *mongo.Database, name string, validator bson.M, indexes []mongo.IndexModel)
MustSetupMongoCollection creates collection if not exists.
func MustValidateMap ¶
MustValidateMap 检查map里的键值类型,是否符合T类型中相同参数名的类型。 map中缺少的参数,或增加的参数,无法被验证。
func NotDeleted ¶
func NotDeleted() int8
func OverwrittenByJWT ¶
func ParseXFTag ¶
func ReloadLogger ¶
func SetLogLevel ¶
func ShortUUID ¶
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 ¶
StringToBytes converts string to byte slice without a memory allocation. Export from github.com/gin-gonic/gin.
func TraceIDFromIncoming ¶
TraceIDFromIncoming extract tid from context. return "" if not found.
func TraceIDFromMD ¶
func TraceIDFromOutgoing ¶
TraceIDFromOutgoing extract tid from context. return "" if not found.
func UniqueIndexOption ¶
func UniqueIndexOption() *options.IndexOptions
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 (*API[T]) MustGetObjReq ¶
func (*API[T]) MustGetPageReq ¶
func (*API[T]) RegisterAPI ¶
func (r *API[T]) RegisterAPI(parent *gin.RouterGroup) (group *gin.RouterGroup)
type AggregateParameters ¶
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 NewCTXWithTraceID ¶
func NewContext ¶
func NewContext() *CTX
func (*CTX) CreateGRPCContext ¶
CreateGRPCContext create a context.Context with header "tid".
func (*CTX) FillGRPCContext ¶
FillGRPCContext append "tid" to context.Context .
func (*CTX) Get ¶
Get returns the value for the given key. If the value does not exist it returns nil.
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 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 (*CommonSvc[T, P]) MustDelete ¶
func (*CommonSvc[T, P]) MustGetList ¶
func (*CommonSvc[T, P]) MustGetPage ¶
func (*CommonSvc[T, P]) MustUpdate ¶
func (*CommonSvc[T, P]) PrepareAdd ¶
func (r *CommonSvc[T, P]) PrepareAdd(doc P)
func (*CommonSvc[T, P]) PrepareDelete ¶
func (*CommonSvc[T, P]) PrepareGet ¶
func (*CommonSvc[T, P]) PreparePageRequest ¶
func (*CommonSvc[T, P]) PrepareSave ¶
func (r *CommonSvc[T, P]) PrepareSave(doc P)
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 ¶
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)
type ErrorPayload ¶
type ErrorType ¶
func ErrAnyError ¶
func ErrDBQueryError ¶
func ErrForbidden ¶
func ErrGRPCDialError ¶
func ErrGeneralError ¶
func ErrInvalidJWTPayload ¶
func ErrInvalidParameters ¶
func ErrMarshalJSONError ¶
func ErrMongoConnectionError ¶
func ErrMongoQueryError ¶
func ErrMongoWriteError ¶
func ErrNotFound ¶
func ErrParamBindingError ¶
func ErrReadRequestBodyError ¶
func ErrServerInternalError ¶
func ErrUnmarshalJSONError ¶
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 ¶
GinHelper provides some helper functions. Respond JSON only.
func NewGinHelper ¶
func (*GinHelper) Bind ¶
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 (*GinHelper) CreateGRPCContext ¶
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 ¶
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 ¶
RespondError responds error in a response in JSON format.
func (*GinHelper) RespondErrorElse ¶
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 (*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 (*GinHelper) RespondKV ¶
RespondKV caller provides one object/array/slice and error, nil if no error. Function will make response properly.
func (*GinHelper) RespondKV200 ¶
func (*GinHelper) RespondKVs ¶
RespondKVs caller provides multiple KV objects and error, nil if no error. Function will make response properly.
func (*GinHelper) RespondKVs200 ¶
func (*GinHelper) UnmarshalJSONToMap ¶
type HandlerFunc ¶
type HandlerFunc func(helper *GinHelper)
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]) MustAddMany ¶
func (r *MongoDAO[T, P]) MustAddMany(docs []P)
func (*MongoDAO[T, P]) MustAggregate ¶
func (*MongoDAO[T, P]) MustDistinct ¶
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 (*MongoDAO[T, P]) MustGetPage ¶
func (*MongoDAO[T, P]) MustHardDelete ¶
func (*MongoDAO[T, P]) MustHardDeleteMany ¶
func (*MongoDAO[T, P]) MustSoftDelete ¶
func (*MongoDAO[T, P]) MustSoftDeleteMany ¶
func (*MongoDAO[T, P]) MustUpdate ¶
func (*MongoDAO[T, P]) MustUpdateMany ¶
func (*MongoDAO[T, P]) MustUpsert ¶
func (*MongoDAO[T, P]) MustUpsertMany ¶
func (*MongoDAO[T, P]) SessionContext ¶
func (*MongoDAO[T, P]) Transaction ¶
Transaction only available for replica set
func (*MongoDAO[T, P]) UseSession ¶
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 TXXWithLogger ¶
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)