Documentation ¶
Index ¶
- Constants
- Variables
- func AgeByBirth(birthday time.Time, now ...time.Time) (age int, unit string)
- func As[T any](v any) T
- func AsOk[T any](v any) (T, bool)
- func Assert[T comparable](handler AssertHandler, l, r T, msgAndArgs ...any)
- func AssertSlice[T comparable](handler AssertHandler, lslice, rslice []T, msgAndArgs ...any)
- func AssertSlicePtr[T comparable](handler AssertHandler, lslice, rslice []*T, msgAndArgs ...any)
- func Batch[S Storer, F Finder[R], R any](db S, finder F, batchNum int, handler func([]R) error) (err error)
- func BatchConcurrent[S Storer, F Finder[R], R any](db S, finder F, batchNum int, handler func([]R) error, concNum int) (err error)
- func BatchRun[T any](s []T, batchNum int, handler func([]T) error) (err error)
- func BatchRunR[T, R any](s []T, batchNum int, handler func([]T) ([]R, error)) (all []R, err error)
- func BinPow(a, b int) int
- func BinPowBig(a, b int) string
- func BytesToString(b []byte) string
- func CallInDefRec[P, R any](c C, p P, f func(C, P) R) R
- func Ceil(x float64, p int) float64
- func CodeIs200(code int) error
- func ConvByName[F, T any](from F, to T)
- func ConvSliceByName[F, T any](from []F, to []T)
- func Copy[T any](v *T) *T
- func Date(year int, month time.Month, day int, loc *time.Location) time.Time
- func DateLocal(year int, month time.Month, day int) time.Time
- func DayZero(t time.Time) time.Time
- func DeepCopy[T any](v T) T
- func Equal[T comparable](l, r T) bool
- func EscapeStruct(v any, escaper Escaper) (err error)
- func EventLoop[I, O, R any](ctx C, n int) (chan<- EventEntity[I, O, R], chan<- struct{})
- func ExecWithBatch[S Storer, Q Queryer](db S, batch []Q) (ra, lid int64, err error)
- func Factorial(n int) int
- func FactorialBig(n int) string
- func FieldWithAlias(field, alias, defaultAlias string) string
- func FieldsByColumnType(t any, colTypes []*sql.ColumnType, fieldMapper func(string) string) (fields []any)
- func FindAll[S Storer, F Finder[R], R any](db S, finder F, initial R) (r []R, err error)
- func FindFirst[S Storer, F Finder[R], R any](db S, finder F, res *R) (err error)
- func FindFirstByFunc[S Storer, F FindFunc[R], R any](db S, finder F, res *R) (err error)
- func FindList[S Storer, F Finder[R], R any](db S, finder F, res *[]R) (err error)
- func FindListByFunc[S Storer, F FindFunc[R], R any](db S, finder F, res *[]R) (err error)
- func FindOne[S Storer, F Finder[R], R any](db S, finder F, initial R) (r R, err error)
- func FindWithBatch[S Storer, B Batcher[R], R any](db S, batcher B, res *[]R) (err error)
- func First[T any](s []T) (t T, ok bool)
- func FirstOr[T any](s []T) (t T)
- func Floor(x float64, p int) float64
- func ForgotKey(key string)
- func FuncName(skip int, withFileInfo bool) string
- func FuzzWrap(v string) string
- func Go[P any](c C, p P, f func(C, P))
- func GoR[P, R any](c C, p P, f func(C, P) R) <-chan R
- func HTMLEscaper(field any) (r any, err error)
- func HTTPProxy(localAddr, remoteAddr string, opt *HTTPProxyOption) (err error)
- func HTTPSProxy(localAddr string, opt *HTTPSProxyOption) (err error)
- func HandleResult(r sql.Result) (id int64, n int64, err error)
- func HashJoin[K comparable, LE, RE, R any](left []LE, right []RE, lk func(item LE) K, rk func(item RE) K, ...) []R
- func Ignore1[T1, T2 any](a1 T1, i T2) T1
- func Ignore2[T1, T2, T3 any](a1 T1, a2 T2, i T3) (T1, T2)
- func Ignore3[T1, T2, T3, T4 any](a1 T1, a2 T2, a3 T3, i T4) (T1, T2, T3)
- func Ignore4[T1, T2, T3, T4, T5 any](a1 T1, a2 T2, a3 T3, a4 T4, i T5) (T1, T2, T3, T4)
- func Ignore5[T1, T2, T3, T4, T5, T6 any](a1 T1, a2 T2, a3 T3, a4 T4, a5 T5, i T6) (T1, T2, T3, T4, T5)
- func In[S comparable](s []S, e S) bool
- func Index[T any](s []T, i int) (t T, ok bool)
- func IndexOr[T any](s []T, i int) (t T)
- func IsComparable[T comparable]()
- func IsExpired(deadline, now time.Time) bool
- func IsPowerOf2(n uint64) bool
- func IsSignDiff(x, y int) bool
- func IsValidIP(ip string) bool
- func IsZero[T comparable](v T) bool
- func JSONExtractor[R any](data []byte) (R, error)
- func JoinUint(parts []uint64) (n uint64)
- func KeyBy[K comparable, E any](collection []E, iteratee func(item E) K) map[K]E
- func KeyValueBy[K comparable, E, V any](collection []E, iteratee func(item E) (K, V)) map[K]V
- func KeyValueGroupBy[K comparable, E, V any](collection []E, iteratee func(item E) (K, V)) map[K][]V
- func Keys[K comparable, E any](collection map[K]E) []K
- func Last[T any](s []T) (t T, ok bool)
- func LastOr[T any](s []T) (t T)
- func Log(err error)
- func Log1[T any](a1 T, err error) T
- func Log2[T1, T2 any](a1 T1, a2 T2, err error) (T1, T2)
- func Log3[T1, T2, T3 any](a1 T1, a2 T2, a3 T3, err error) (T1, T2, T3)
- func Log4[T1, T2, T3, T4 any](a1 T1, a2 T2, a3 T3, a4 T4, err error) (T1, T2, T3, T4)
- func Log5[T1, T2, T3, T4, T5 any](a1 T1, a2 T2, a3 T3, a4 T4, a5 T5, err error) (T1, T2, T3, T4, T5)
- func MakeSlice[T any](l int) (to []*T)
- func MapFrom[T any, R interface{ ... }](s []T, initial func() R) []R
- func MapFrom2[T any, R interface{ ... }](s []T) []R
- func MapSlicePtr[T *R, R any](s []T) []R
- func MapTo[T interface{ ... }, R any](s []T) []R
- func MapTo2[T interface{ ... }, R any](s []T) []R
- func MatchError(v any) bool
- func MergeKeyValue[K comparable, V any](m1, m2 map[K]V) map[K]V
- func MkdirAllIfNotExist(dir string) error
- func MonthFirst(t time.Time) time.Time
- func MultipartBody(body io.Writer, fieldname, filename string, data []byte) (fileContentType string, err error)
- func Must(err error)
- func Must1[T any](a1 T, err error) T
- func Must2[T1, T2 any](a1 T1, a2 T2, err error) (T1, T2)
- func Must3[T1, T2, T3 any](a1 T1, a2 T2, a3 T3, err error) (T1, T2, T3)
- func Must4[T1, T2, T3, T4 any](a1 T1, a2 T2, a3 T3, a4 T4, err error) (T1, T2, T3, T4)
- func Must5[T1, T2, T3, T4, T5 any](a1 T1, a2 T2, a3 T3, a4 T4, a5 T5, err error) (T1, T2, T3, T4, T5)
- func NestedJoin[J, K, R any](left []J, right []K, match func(J, K) bool, mapper func(J, K) R) []R
- func NewError[T any](inner T) error
- func NewHTTPClient(opts ...HTTPClientSetter) *http.Client
- func ObjectAndFieldsHelper[T any](fieldMappers ...func(string) string) func(colTypes []*sql.ColumnType) (r *T, fields []any)
- func Or[T comparable](vals ...T) T
- func ParseTime(t string, layouts ...string) (r time.Time, err error)
- func Pointer[T any]() *T
- func Pow10(n int) (r uint64)
- func PrintFields(fields []any)
- func ProxyTraceBegin(pctx ProxyContext, extras ...any) (stop func(args ...any))
- func RawExtractor(data []byte) ([]byte, error)
- func Rectangle[T any](m, n int, initial ...T) [][]T
- func RegisterProxyMethod(pctx ProxyContext, cf ProxyCtxFunc, typeParams ...string)
- func RegisterProxyTracer(tracers ...Tracer)
- func RegisterRouter[H RouteRegister, RH RouteHandler[P, R], P, R any](g H, rh RH, method, path string, f func(context.Context, P) (R, error))
- func ReplaceIP(link, ip, nip string) (r string, err error)
- func RetryWithDeadline(ctx context.Context, d time.Time, f Doer) error
- func RetryWithTimes(ctx context.Context, tryTimes int, f Doer) error
- func Return1[T any](a1 T, err error) T
- func Round(x float64, p int) float64
- func RunWithTimeout[P, R any](ctx C, d time.Duration, p P, f func(ctx C, p P) R) (r R, ok bool)
- func SendHTTPRequest[R any](client *http.Client, method string, link string, body io.Reader, ...) (R, error)
- func SingleFlight[R any](key string, fn SingleFlightCall[R]) (r R, err error)
- func SplitUint(n uint64) []uint64
- func Square[T any](n int, initial ...T) [][]T
- func StreamRun[T any](s chan T, batchNum int, handler func([]T) error) (err error)
- func StreamRunR[T, R any](s chan T, batchNum int, handler func([]T) ([]R, error)) (all []R, err error)
- func StringToBytes(s string) []byte
- func SwapByBit(a, b int) (int, int)
- func TCPProxy(localAddr, remoteAddr string, handlers ...func(lconn, rconn net.Conn)) (err error)
- func TCPProxyDefaultHandler(lconn, rconn net.Conn)
- func TCPRecv(localAddr string, handler func(conn net.Conn)) (err error)
- func TCPSend(remoteAddr string, handler func(conn net.Conn) error) (err error)
- func ThisMonthFirst() time.Time
- func ThisYearFirst() time.Time
- func TodayZero() time.Time
- func Unique[S comparable](s []S) []S
- func ValueAs[K comparable, T any](m *Map[K, any], key K) T
- func ValueOf[F any](v any, field string) (f F, ok bool)
- func Values[K comparable, E any](collection map[K]E) []E
- func WithWhere[T comparable](t T, cond func(field string, value interface{}) string, field string, ...) string
- func WrapConnFindAll[F Finder[R], R any](ctx context.Context, db *sql.DB, finder F, initial R) (r []R, err error)
- func WrapDB(ctx context.Context, driverName string, dataSourceName string, ...) error
- func WrapSQLConn(ctx context.Context, db *sql.DB, ...) error
- func WrapSQLConnV[R any](ctx context.Context, db *sql.DB, ...) (r R, err error)
- func WrapSQLQueryRows(ctx context.Context, db *sql.DB, stmt string, args []interface{}, ...) error
- func WrapTx(ctx context.Context, db *sql.DB, f func(ctx context.Context, tx *sql.Tx) error) (err error)
- func WrapTxFindAll[F Finder[R], R any](ctx context.Context, db *sql.DB, finder F, initial R) (r []R, err error)
- func WrapTxV[R any](ctx context.Context, db *sql.DB, ...) (r R, err error)
- func XMLEscaper(field any) (r any, err error)
- func XMLExtractor[R any](data []byte) (R, error)
- func YearFirst(t time.Time) time.Time
- func Zero[T any]() T
- type APIType
- type APITypeCtxHelper
- type AssertHandler
- type Batcher
- type C
- type CheckDataPerm
- type CheckDataPermCtxHelper
- type CircuitBreaker
- type Claims
- type CodeChecker
- type ContextHelper
- type Counts
- type Crypto
- type DataPermJoinType
- type DataPermJoinTypeCtxHelper
- type DataPermType
- type DataPermTypeCtxHelper
- type DecodeFunc
- type Decoder
- type DoWithCtx
- type Doer
- type E
- func CallInDefRec2[P, R any](c C, p P, f func(C, P) (R, E)) (r R, e E)
- func Event[I, O, R any](ctx C, param I, do PipeFunc[I, O], success PipeFunc[O, R], ...) (r R, err E)
- func Pipe[B, D, A, R any](ctx C, b B, before PipeFunc[B, D], do PipeFunc[D, A], after PipeFunc[A, R]) (r R, err E)
- func Pipes[B, D, A, R any](ctx C, b B, before Piper[B, D], do Piper[D, A], after Piper[A, R]) (r R, e E)
- func RunIf[P, R any, F LogicSet[P, R]](cond bool, ctx C, param P, f F) (r R, err E)
- func RunLogicIf[P, R any](cond bool, ctx C, param P, f Logic[P, R]) (r R, err E)
- type Entity
- type EntityWithTotal
- type Enum
- type EnvType
- type EnvTypeCtxHelper
- type Error
- type ErrorHandler
- type Escaper
- type EventEntity
- type EventFunc
- type Field
- type FindFunc
- type Finder
- type HTTPClientOption
- type HTTPClientSetter
- type HTTPProxyOption
- type HTTPSProxyOption
- type HandlerFunc
- type Id
- type IdType
- type IdsType
- type Interface
- type Ioc
- type IocOption
- type IsAdminType
- type IsAdminTypeCtxHelper
- type Job
- type KeyOption
- type ListResult
- type Logic
- func LogicFrom[P, R any](f func(C, P) (R, E)) Logic[P, R]
- func LogicFromWE[P, R any](f func(C, P) R) Logic[P, R]
- func LogicFromWP[R any](f func(C) (R, E)) Logic[struct{}, R]
- func LogicFromWPE[R any](f func(C) R) Logic[struct{}, R]
- func LogicFromWPR(f func(C) E) Logic[struct{}, struct{}]
- func LogicFromWPRE(f func(C)) Logic[struct{}, struct{}]
- func LogicFromWR[P any](f func(C, P) E) Logic[P, struct{}]
- func LogicFromWRE[P any](f func(C, P)) Logic[P, struct{}]
- func PipeToLogic[I, O any](pf PipeFunc[I, O]) Logic[I, O]
- type LogicSet
- type LogicWithoutError
- type LogicWithoutPR
- type LogicWithoutParam
- type LogicWithoutParamError
- type LogicWithoutParamResultError
- type LogicWithoutResult
- type LogicWithoutResultError
- type Map
- type NotSaveCtxHelper
- type NotSaveType
- type PageCond
- type PageResult
- type Pager
- type ParamData
- type ParamParser
- type Password
- type PipeFunc
- type Piper
- type ProxyContext
- type ProxyCtxFunc
- type ProxyCtxFuncStore
- type Queryer
- type RemoteAddrType
- type RemoteAddrTypeCtxHelper
- type RequestKeyType
- type RequestKeyTypeCtxHelper
- type RespHeaderExtractor
- type ResultExtractor
- type Route
- type RouteHandler
- type RouteOption
- type RouteRegister
- type Settings
- type Signer
- type SingleFlightCall
- type Slice
- type State
- type StateFunc
- type StateMachine
- type Storer
- type Struct
- type StructCommentEntity
- type TimeTracer
- type TimestampType
- type TimestampTypeCtxHelper
- type ToLogic
- type Token
- type TraceId
- type TraceKey
- type Tracer
- type TreeEntity
- type TwoStepCircuitBreaker
- type UserKeyType
- type UserKeyTypeCtxHelper
- type Worker
Constants ¶
const ( DateTimeFormat = "2006-01-02 15:04:05" DateFormat = "2006-01-02" )
Variables ¶
var ( // ErrTooManyRequests is returned when the CB state is half open and the requests count is over the cb maxRequests ErrTooManyRequests = errors.New("too many requests") // ErrOpenState is returned when the CB state is open ErrOpenState = errors.New("circuit breaker is open") )
var ( ErrBadIssuer = errors.New("Token Bad Issuer") ErrExpired = errors.New("Token Expired") ErrNotValid = errors.New("Token Not Valid") )
var ( ErrWorkerIsStop = errors.New("Worker is stop") ErrNilJobDo = errors.New("Job do field is nil") )
var (
ErrNilDoer = errors.New("f is nil")
)
var (
Location = time.FixedZone("CST", 8*3600) // 东八,Asia/Shanghai
)
Functions ¶
func AgeByBirth ¶ added in v1.1.0
AgeByBirth get age and unit by birthday. It will use time.Now() if not input now. If exist year, ignore month and day; If exist month, ignore day.
func Assert ¶ added in v0.33.0
func Assert[T comparable](handler AssertHandler, l, r T, msgAndArgs ...any)
func AssertSlice ¶ added in v0.61.0
func AssertSlice[T comparable](handler AssertHandler, lslice, rslice []T, msgAndArgs ...any)
func AssertSlicePtr ¶ added in v1.11.0
func AssertSlicePtr[T comparable](handler AssertHandler, lslice, rslice []*T, msgAndArgs ...any)
func Batch ¶ added in v0.2.0
func Batch[S Storer, F Finder[R], R any](db S, finder F, batchNum int, handler func([]R) error) (err error)
Batch process data find from Storer in batches
func BatchConcurrent ¶ added in v0.2.0
func BatchConcurrent[S Storer, F Finder[R], R any](db S, finder F, batchNum int, handler func([]R) error, concNum int) (err error)
BatchConcurrent batch process data concurrently
func BinPow ¶ added in v1.22.0
BinPow return a**b with binary pow. if `a` or `b` is very big, use `BinPowBig` instead
func BytesToString ¶ added in v0.5.0
BytesToString converts byte slice to string without a memory allocation.
func CallInDefRec ¶ added in v0.85.0
CallInDefRec run f with defer recover to catch panic
func ConvByName ¶ added in v0.54.0
func ConvByName[F, T any](from F, to T)
ConvByName fill 'to' struct with 'from' by name like to.Name = from.Name to must be a struct pointer
func ConvSliceByName ¶ added in v0.54.0
func ConvSliceByName[F, T any](from []F, to []T)
ConvSliceByName fill 'to' struct slice with 'from' by name
func Copy ¶ added in v0.88.0
func Copy[T any](v *T) *T
Copy return a copy of v's value without deep copy. If you need deep copy, use DeepCody instead.
func DeepCopy ¶ added in v0.90.0
func DeepCopy[T any](v T) T
Copy creates a deep copy of whatever is passed to it and returns the copy in an interface{}. The returned value will need to be asserted to the correct type. It will not copy unexported fields.
func Equal ¶ added in v0.33.0
func Equal[T comparable](l, r T) bool
func EscapeStruct ¶ added in v1.2.0
EscapeStruct escape struct field value with escaper, v must be a struct pointer
func ExecWithBatch ¶ added in v0.35.0
ExecWithBatch exec with batch
func Factorial ¶ added in v1.4.0
Factorial n <= 20, it will return 0 if n > 20, use FactorialBig instead.
func FieldWithAlias ¶ added in v0.53.0
FieldWithAlias use alias if not empty, or use defaultAlias
func FieldsByColumnType ¶ added in v0.10.0
func FieldsByColumnType(t any, colTypes []*sql.ColumnType, fieldMapper func(string) string) (fields []any)
FieldsByColumnType t is a struct pointer, and use it's field match column name to receive scan value. It will use db tag to get column name first, or lower case field name. You can specify fieldMapper to control column name with field name
func FindFirstByFunc ¶ added in v0.16.0
func FindListByFunc ¶ added in v0.16.0
func FindWithBatch ¶ added in v0.35.0
FindWithBatch use batchFunc to split args to little batch, for example: args is 1, [1, 2, 3], split to 3 batch is: 1, [1]; 1, [2]; 3, [3], the slice become little while the others is not change
func HTMLEscaper ¶ added in v1.2.0
func HTTPProxy ¶ added in v0.27.0
func HTTPProxy(localAddr, remoteAddr string, opt *HTTPProxyOption) (err error)
HTTPProxy listen localAddr and transfer any request to remoteAddr. We can use handlers to specify one custom func to transfer data.
func HTTPSProxy ¶ added in v1.14.0
func HTTPSProxy(localAddr string, opt *HTTPSProxyOption) (err error)
func HandleResult ¶ added in v0.89.0
HandleResult check affected rows first, if it is not zero then get last insert id
func HashJoin ¶ added in v0.2.0
func HashJoin[K comparable, LE, RE, R any]( left []LE, right []RE, lk func(item LE) K, rk func(item RE) K, mapper func(LE, RE) R, ) []R
HashJoin like hash join
func Ignore1 ¶ added in v0.52.0
func Ignore1[T1, T2 any](a1 T1, i T2) T1
Ignore1 ignore the last variable,and continue with 1 result
func Ignore2 ¶ added in v0.52.0
func Ignore2[T1, T2, T3 any](a1 T1, a2 T2, i T3) (T1, T2)
Ignore2 ignore the last variable,and continue with 2 result
func Ignore3 ¶ added in v0.52.0
func Ignore3[T1, T2, T3, T4 any](a1 T1, a2 T2, a3 T3, i T4) (T1, T2, T3)
Ignore3 ignore the last variable,and continue with 3 result
func Ignore4 ¶ added in v0.52.0
func Ignore4[T1, T2, T3, T4, T5 any](a1 T1, a2 T2, a3 T3, a4 T4, i T5) (T1, T2, T3, T4)
Ignore4 ignore the last variable,and continue with 4 result
func Ignore5 ¶ added in v0.52.0
func Ignore5[T1, T2, T3, T4, T5, T6 any](a1 T1, a2 T2, a3 T3, a4 T4, a5 T5, i T6) (T1, T2, T3, T4, T5)
Ignore5 ignore the last variable,and continue with 5 result
func In ¶ added in v0.82.0
func In[S comparable](s []S, e S) bool
func IsComparable ¶ added in v0.8.0
func IsComparable[T comparable]()
IsComparable check if a type is comparable in compile time
func IsExpired ¶ added in v0.11.0
IsExpired show if deadline is expired compared to now always return false if deadline is zero
func IsPowerOf2 ¶ added in v1.11.0
func IsSignDiff ¶ added in v1.11.0
func IsZero ¶ added in v0.12.0
func IsZero[T comparable](v T) bool
func JSONExtractor ¶ added in v0.2.0
func KeyBy ¶ added in v0.2.0
func KeyBy[K comparable, E any](collection []E, iteratee func(item E) K) map[K]E
KeyBy slice to map, key specified by iteratee, value is slice element
func KeyValueBy ¶ added in v0.2.0
func KeyValueBy[K comparable, E, V any](collection []E, iteratee func(item E) (K, V)) map[K]V
KeyValueBy slice to map, key value specified by iteratee
func KeyValueGroupBy ¶ added in v1.16.0
func KeyValueGroupBy[K comparable, E, V any](collection []E, iteratee func(item E) (K, V)) map[K][]V
KeyValueGroupBy []int{{id: 1, from: gd}, {id: 2, from: gd}} -> map[string][]int{gd: []int{1, 2}}
func Keys ¶ added in v0.8.0
func Keys[K comparable, E any](collection map[K]E) []K
func Log5 ¶ added in v0.32.0
func Log5[T1, T2, T3, T4, T5 any](a1 T1, a2 T2, a3 T3, a4 T4, a5 T5, err error) (T1, T2, T3, T4, T5)
Log5 log the err if err is not nill,and continue with 5 result
func MapFrom ¶ added in v1.11.0
func MapFrom[T any, R interface{ From(T) }](s []T, initial func() R) []R
func MapSlicePtr ¶ added in v1.15.0
func MapSlicePtr[T *R, R any](s []T) []R
func MatchError ¶
func MergeKeyValue ¶ added in v0.15.0
func MergeKeyValue[K comparable, V any](m1, m2 map[K]V) map[K]V
MergeKeyValue merge m2 into m1, will override m1 key value if both exists
func MkdirAllIfNotExist ¶ added in v0.8.0
func MultipartBody ¶ added in v0.23.0
func MultipartBody(body io.Writer, fieldname, filename string, data []byte) (fileContentType string, err error)
MultipartBody new a multipart writer with body, mark with fieldname and name, write data to it. Return form data content type.
func Must5 ¶
func Must5[T1, T2, T3, T4, T5 any](a1 T1, a2 T2, a3 T3, a4 T4, a5 T5, err error) (T1, T2, T3, T4, T5)
Must5 panic if err is not nill,or return 5 result
func NestedJoin ¶ added in v0.2.0
func NestedJoin[J, K, R any]( left []J, right []K, match func(J, K) bool, mapper func(J, K) R, ) []R
NestedJoin like nested loop join
func NewHTTPClient ¶ added in v0.91.0
func NewHTTPClient(opts ...HTTPClientSetter) *http.Client
func ObjectAndFieldsHelper ¶ added in v0.41.0
func ObjectAndFieldsHelper[T any](fieldMappers ...func(string) string) func(colTypes []*sql.ColumnType) (r *T, fields []any)
ObjectAndFieldsHelper if *T is interface{ ValuePtrs() []any } then use its results as fields, otherwise use reflect to get fields by ColumnType
func Or ¶ added in v1.9.0
func Or[T comparable](vals ...T) T
Or returns the first of its arguments that is not equal to the zero value. If no argument is non-zero, it returns the zero value.
func ParseTime ¶ added in v0.18.0
ParseTime parse time string t with layout s one by one; if layouts is empty, it will use "2006-01-02 15:04:05" as default
func PrintFields ¶ added in v0.2.0
func PrintFields(fields []any)
func ProxyTraceBegin ¶ added in v0.13.0
func ProxyTraceBegin(pctx ProxyContext, extras ...any) (stop func(args ...any))
ProxyTraceBegin LIFO
func RawExtractor ¶ added in v0.25.0
func RegisterProxyMethod ¶ added in v0.14.0
func RegisterProxyMethod(pctx ProxyContext, cf ProxyCtxFunc, typeParams ...string)
RegisterProxyMethod 注册代理方法,根据包名+接口名+方法名唯一对应一个方法;在有了泛型后还要加上类型参数,唯一键变为包名+接口名+方法名+TP1,TP2,...
func RegisterProxyTracer ¶ added in v0.13.0
func RegisterProxyTracer(tracers ...Tracer)
func RegisterRouter ¶ added in v0.34.0
func RegisterRouter[H RouteRegister, RH RouteHandler[P, R], P, R any]( g H, rh RH, method, path string, f func(context.Context, P) (R, error), )
RegisterRouter register router to RouteRegister with http.HandlerFunc
func RetryWithDeadline ¶ added in v0.5.0
RetryWithDeadline retry f before d exceeds if f failed
func RetryWithTimes ¶ added in v0.5.0
RetryWithTimes retry f tryTimes times if f failed
func RunWithTimeout ¶ added in v0.87.0
RunWithTimeout run func with timeout, return even if the func haven't completed. `ok` will report if the func has completed
func SendHTTPRequest ¶ added in v0.2.0
func SendHTTPRequest[R any]( client *http.Client, method string, link string, body io.Reader, header http.Header, codeChecker CodeChecker, extractResult ResultExtractor[R], ) (R, error)
SendHTTPRequest send http request and get result of type R. If you want to got resp header, the R should implement RespHeaderExtractor interface.
func SingleFlight ¶ added in v0.6.0
func SingleFlight[R any](key string, fn SingleFlightCall[R]) (r R, err error)
SingleFlight make sure only one request is doing with one key
func StreamRun ¶ added in v0.36.0
StreamRun handle data by stream, if batchNum is >0, run with batch
func StreamRunR ¶ added in v1.17.0
func StreamRunR[T, R any](s chan T, batchNum int, handler func([]T) ([]R, error)) (all []R, err error)
StreamRunR handle data by stream, if batchNum is >0, run with batch
func StringToBytes ¶ added in v0.5.0
StringToBytes converts string to byte slice without a memory allocation.
func TCPProxy ¶ added in v0.19.0
TCPProxy listen localAddr and transfer any request to remoteAddr.We can use handlers to specify one custom func to transfer data.
func TCPProxyDefaultHandler ¶ added in v0.20.0
func TCPRecv ¶ added in v0.19.0
TCPRecv recv from local addr with handler, it will block on (*net.TCPListener).Accept
func ThisMonthFirst ¶ added in v0.12.0
func ThisYearFirst ¶ added in v0.12.0
func Unique ¶ added in v0.82.0
func Unique[S comparable](s []S) []S
func ValueAs ¶ added in v0.8.0
func ValueAs[K comparable, T any](m *Map[K, any], key K) T
ValueAs get value by key from *Map[K, any], and assert value type to T
func Values ¶ added in v0.8.0
func Values[K comparable, E any](collection map[K]E) []E
func WithWhere ¶ added in v0.53.0
func WithWhere[T comparable]( t T, cond func(field string, value interface{}) string, field string, value ...T, ) string
WithWhere return condition if t is not a zero value of T
func WrapConnFindAll ¶ added in v0.2.0
func WrapConnFindAll[F Finder[R], R any]( ctx context.Context, db *sql.DB, finder F, initial R, ) (r []R, err error)
WrapConnFindAll query by stmt and args, return values with dest support many rows
func WrapSQLConn ¶ added in v0.2.0
func WrapSQLConnV ¶ added in v1.22.0
func WrapSQLQueryRows ¶ added in v0.2.0
func WrapSQLQueryRows( ctx context.Context, db *sql.DB, stmt string, args []interface{}, dest ...interface{}, ) error
WrapSQLQueryRows query by stmt and args, return values with dest only support one row
func WrapTxFindAll ¶ added in v0.2.0
func XMLEscaper ¶ added in v1.2.0
func XMLExtractor ¶ added in v0.2.0
Types ¶
type APITypeCtxHelper ¶ added in v1.23.0
type APITypeCtxHelper = ContextHelper[APIType, string]
type AssertHandler ¶ added in v0.33.0
type CheckDataPermCtxHelper ¶ added in v1.23.0
type CheckDataPermCtxHelper = ContextHelper[CheckDataPerm, bool]
type CircuitBreaker ¶ added in v0.30.0
type CircuitBreaker[P, R any] struct { // contains filtered or unexported fields }
CircuitBreaker is a state machine to prevent sending requests that are likely to fail.
func NewCircuitBreaker ¶ added in v0.30.0
func NewCircuitBreaker[P, R any](st Settings) *CircuitBreaker[P, R]
NewCircuitBreaker returns a new CircuitBreaker configured with the given Settings.
func (*CircuitBreaker[P, R]) Counts ¶ added in v0.30.0
func (cb *CircuitBreaker[P, R]) Counts() Counts
Counts returns internal counters
func (*CircuitBreaker[P, R]) Execute ¶ added in v0.30.0
func (cb *CircuitBreaker[P, R]) Execute(param P, req func(p P) (R, error)) (r R, err error)
Execute runs the given request if the CircuitBreaker accepts it. Execute returns an error instantly if the CircuitBreaker rejects the request. Otherwise, Execute returns the result of the request. If a panic occurs in the request, the CircuitBreaker handles it as an error and causes the same panic again.
func (*CircuitBreaker[P, R]) Name ¶ added in v0.30.0
func (cb *CircuitBreaker[P, R]) Name() string
Name returns the name of the CircuitBreaker.
func (*CircuitBreaker[P, R]) State ¶ added in v0.30.0
func (cb *CircuitBreaker[P, R]) State() State
State returns the current state of the CircuitBreaker.
type CodeChecker ¶ added in v0.2.0
type ContextHelper ¶ added in v0.37.0
type ContextHelper[K ~struct{}, V any] struct { // contains filtered or unexported fields }
func (ContextHelper[K, V]) MustValue ¶ added in v0.37.0
func (h ContextHelper[K, V]) MustValue(ctx context.Context) (v V)
type Counts ¶ added in v0.30.0
type Counts struct { Requests uint32 TotalSuccesses uint32 TotalFailures uint32 ConsecutiveSuccesses uint32 ConsecutiveFailures uint32 }
Counts holds the numbers of requests and their successes/failures. CircuitBreaker clears the internal Counts either on the change of the state or at the closed-state intervals. Counts ignores the results of the requests sent before clearing.
type Crypto ¶ added in v0.56.0
type Crypto struct {
// contains filtered or unexported fields
}
func NewCrypto ¶ added in v0.56.0
NewCrypto NewCrypto key: 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
type DataPermJoinTypeCtxHelper ¶ added in v1.23.0
type DataPermJoinTypeCtxHelper = ContextHelper[DataPermJoinType, [][]string]
type DataPermTypeCtxHelper ¶ added in v1.23.0
type DataPermTypeCtxHelper = ContextHelper[DataPermType, string]
type DecodeFunc ¶ added in v0.28.0
func (DecodeFunc[T]) Decode ¶ added in v0.28.0
func (f DecodeFunc[T]) Decode(src T, v any) error
type E ¶ added in v0.24.0
type E = error
func CallInDefRec2 ¶ added in v1.19.0
CallInDefRec2 run f with defer recover to catch panic
func Event ¶ added in v0.24.0
func Event[I, O, R any]( ctx C, param I, do PipeFunc[I, O], success PipeFunc[O, R], failed PipeFunc[E, R], ) (r R, err E)
Event do something with input I, handle result with success or failed
func Pipe ¶ added in v0.24.0
func Pipe[B, D, A, R any]( ctx C, b B, before PipeFunc[B, D], do PipeFunc[D, A], after PipeFunc[A, R], ) (r R, err E)
Pipe is a pipe run the PipeFuncs in order
type EntityWithTotal ¶ added in v0.62.0
EntityWithTotal used to scan col1, col2, col3 to T, and scan total to Total when columns is [col1, col2, col3, total] if *T is interface{ ValuePtrs() []any }
func (*EntityWithTotal[T]) ValuePtrs ¶ added in v0.62.0
func (s *EntityWithTotal[T]) ValuePtrs() []any
ValuePtrs return T's fields and Total's pointer if *T is interface{ ValuePtrs() []any }, or return Inner and Total's pointer; use by rows.Scan(s.ValuePtrs()....)
type EnvTypeCtxHelper ¶ added in v1.23.0
type EnvTypeCtxHelper = ContextHelper[EnvType, string]
type Error ¶
type Error[T any] struct { // contains filtered or unexported fields }
Error is a error type with any element
func ConvertError ¶
type ErrorHandler ¶ added in v0.2.0
type ErrorHandler func(error)
type EventEntity ¶ added in v0.25.0
type Field ¶ added in v0.9.0
type Field struct { reflect.StructField // 内嵌反射结构体字段类型 Comment string // 注释 Struct Struct // 字段的类型是其它结构体 }
type FindFunc ¶ added in v0.16.0
type FindFunc[R any] func() (query string, args []any, genObj func(colTypes []*sql.ColumnType) (r *R, fields []any))
FindFunc return query, args, and object generator; object generator should return new object and it's related fields when called; FindFunc is a Finder too.
func FindFuncHelper ¶ added in v0.45.0
func FindFuncHelper[T any]( query string, args []any, fieldMappers ...func(string) string, ) FindFunc[T]
FindFuncHelper return FindFunc with T
func (FindFunc[R]) NewScanObjAndFields ¶ added in v0.16.0
func (f FindFunc[R]) NewScanObjAndFields(colTypes []*sql.ColumnType) (r *R, fields []any)
type Finder ¶ added in v0.2.0
type Finder[R any] interface { Queryer // new a result type object, not the same, to receive every row // fields must be pointer type of result object's field, and it is match with query sql's select column one by one NewScanObjAndFields(colTypes []*sql.ColumnType) (r *R, fields []any) }
type HTTPClientOption ¶ added in v0.91.0
type HTTPClientOption struct {
// contains filtered or unexported fields
}
type HTTPClientSetter ¶ added in v0.91.0
type HTTPClientSetter func(*HTTPClientOption)
func HTTPClientSkipVerify ¶ added in v0.91.0
func HTTPClientSkipVerify() HTTPClientSetter
func HTTPClientWithTimeout ¶ added in v0.91.0
func HTTPClientWithTimeout(timeout time.Duration) HTTPClientSetter
func HTTPClientWithTransport ¶ added in v0.91.0
func HTTPClientWithTransport(tp *http.Transport) HTTPClientSetter
type HTTPProxyOption ¶ added in v0.27.0
type HTTPSProxyOption ¶ added in v1.14.0
type HandlerFunc ¶ added in v0.79.0
type HandlerFunc[T any] func(T)
func (HandlerFunc[T]) HTTPHandlerFunc ¶ added in v0.79.0
func (h HandlerFunc[T]) HTTPHandlerFunc(t T) http.HandlerFunc
type Id ¶ added in v0.56.0
type Id uint64
Id to/from string when json encode/decode
func (Id) MarshalJSON ¶ added in v0.56.0
func (*Id) UnmarshalJSON ¶ added in v0.56.0
type IdsType ¶ added in v0.72.0
type IdsType[T any] struct { Ids []T `json:"ids" form:"ids"` // ids }
type Interface ¶ added in v0.90.0
type Interface interface {
DeepCopy() interface{}
}
Interface for delegating copy process to type
type Ioc ¶ added in v0.29.0
type Ioc struct {
// contains filtered or unexported fields
}
Ioc Inversion of Control, dependency inject
func (*Ioc) Inject ¶ added in v0.29.0
Inject init v with providers. v is a struct pointer.
If provider need parameters, it will lookup a right value by it's type.
func (*Ioc) RegisterProvider ¶ added in v0.29.0
RegisterProvider register provider,like `func New(fielda TypeA, fieldb TypeB) (T)`
type IsAdminTypeCtxHelper ¶ added in v1.23.0
type IsAdminTypeCtxHelper = ContextHelper[IsAdminType, bool]
type ListResult ¶ added in v0.72.0
type ListResult[T any] struct { List []T `json:"list" fakesize:"1"` // list }
type Logic ¶ added in v1.6.0
func LogicFromWE ¶ added in v1.10.0
func LogicFromWPE ¶ added in v1.10.0
func LogicFromWPR ¶ added in v1.10.0
func LogicFromWPRE ¶ added in v1.10.0
func LogicFromWRE ¶ added in v1.10.0
func PipeToLogic ¶ added in v1.7.0
type LogicWithoutError ¶ added in v1.6.0
type LogicWithoutPR ¶ added in v1.6.0
type LogicWithoutParam ¶ added in v1.6.0
type LogicWithoutParamError ¶ added in v1.6.0
type LogicWithoutParamResultError ¶ added in v1.6.0
type LogicWithoutParamResultError func(C)
type LogicWithoutResult ¶ added in v1.6.0
type LogicWithoutResultError ¶ added in v1.6.0
type Map ¶ added in v0.6.0
type Map[K comparable, T any] struct { // contains filtered or unexported fields }
type NotSaveCtxHelper ¶ added in v1.23.0
type NotSaveCtxHelper = ContextHelper[NotSaveType, bool]
type PageCond ¶ added in v1.23.0
type PageCond[T, C any] struct { Table T Cond C }
func PageCondFrom ¶ added in v1.23.0
type PageResult ¶ added in v0.63.0
type Pager ¶ added in v0.56.0
type ParamParser ¶ added in v0.28.0
type ParamParser[T ParamData] struct { // contains filtered or unexported fields }
func NewParamParser ¶ added in v0.28.0
func NewParamParser[T ParamData](decoder Decoder[T]) *ParamParser[T]
func (*ParamParser[T]) Parse ¶ added in v0.28.0
func (p *ParamParser[T]) Parse(data T, v any) error
Parse parse data to v with decoder.
func (*ParamParser[T]) ParseAndCheck ¶ added in v0.28.0
func (p *ParamParser[T]) ParseAndCheck(ctx context.Context, data T, v any) error
ParseAndCheck parse data to v with decoder and check v if v implement interface{ Check(context.Context) error } or interface{ Check() error }.
type Password ¶ added in v0.56.0
type Password string
type PipeFunc ¶ added in v0.24.0
func PipeFromLogic ¶ added in v1.7.0
type ProxyContext ¶ added in v0.13.0
每个包、每个接口、每个方法唯一对应一个方法
func (ProxyContext) IsEmpty ¶ added in v0.13.0
func (pctx ProxyContext) IsEmpty() bool
func (ProxyContext) LogShortf ¶ added in v0.13.0
func (pctx ProxyContext) LogShortf(format string, args ...any)
func (ProxyContext) Logf ¶ added in v0.13.0
func (pctx ProxyContext) Logf(format string, args ...any)
func (ProxyContext) String ¶ added in v0.13.0
func (pctx ProxyContext) String() string
func (ProxyContext) Uniq ¶ added in v0.13.0
func (pctx ProxyContext) Uniq() string
type ProxyCtxFunc ¶ added in v0.13.0
type ProxyCtxFunc func(ctx ProxyContext, method any, args []any) (res []any)
ProxyCtxFunc 对于method: func(string, int) (int, error) f := method.(func(string, int) (int, error)) a1 := args[0].(string) a2 := args[1].(int) r1, r2 := f(a1, a2) res = append(res, r1, r2)
type ProxyCtxFuncStore ¶ added in v0.13.0
type ProxyCtxFuncStore struct {
// contains filtered or unexported fields
}
func GlobalProxyCtxMap ¶ added in v0.14.0
func GlobalProxyCtxMap() *ProxyCtxFuncStore
func NewProxyCtxMap ¶ added in v0.13.0
func NewProxyCtxMap() *ProxyCtxFuncStore
func (*ProxyCtxFuncStore) Lookup ¶ added in v0.13.0
func (m *ProxyCtxFuncStore) Lookup(pctx ProxyContext, typeParams ...string) (ProxyCtxFunc, bool)
func (*ProxyCtxFuncStore) Set ¶ added in v0.13.0
func (m *ProxyCtxFuncStore) Set(pctx ProxyContext, f ProxyCtxFunc, typeParams ...string)
type RemoteAddrTypeCtxHelper ¶ added in v1.23.0
type RemoteAddrTypeCtxHelper = ContextHelper[RemoteAddrType, string]
type RequestKeyTypeCtxHelper ¶ added in v1.23.0
type RequestKeyTypeCtxHelper = ContextHelper[RequestKeyType, string]
type RespHeaderExtractor ¶ added in v0.21.0
type ResultExtractor ¶ added in v0.2.0
type Route ¶ added in v0.79.0
type Route[T any] struct { Method string Path string Comment string Opt *RouteOption Handler HandlerFunc[T] Childs []*Route[T] }
func NewRoute ¶ added in v0.79.0
func NewRoute[T any](method, path, comment string, h HandlerFunc[T], childs ...*Route[T]) *Route[T]
func (*Route[T]) WithChilds ¶ added in v0.79.0
func (*Route[T]) WithOption ¶ added in v0.92.0
func (r *Route[T]) WithOption(opt *RouteOption) *Route[T]
type RouteHandler ¶ added in v0.34.0
type RouteOption ¶ added in v0.92.0
type RouteRegister ¶ added in v0.34.0
type RouteRegister interface {
Handle(method, path string, handlers http.HandlerFunc)
}
type Settings ¶ added in v0.30.0
type Settings struct { Name string MaxRequests uint32 Interval time.Duration Timeout time.Duration ReadyToTrip func(counts Counts) bool OnStateChange func(name string, from State, to State) IsSuccessful func(err error) bool }
Settings configures CircuitBreaker:
Name is the name of the CircuitBreaker.
MaxRequests is the maximum number of requests allowed to pass through when the CircuitBreaker is half-open. If MaxRequests is 0, the CircuitBreaker allows only 1 request.
Interval is the cyclic period of the closed state for the CircuitBreaker to clear the internal Counts. If Interval is less than or equal to 0, the CircuitBreaker doesn't clear internal Counts during the closed state.
Timeout is the period of the open state, after which the state of the CircuitBreaker becomes half-open. If Timeout is less than or equal to 0, the timeout value of the CircuitBreaker is set to 60 seconds.
ReadyToTrip is called with a copy of Counts whenever a request fails in the closed state. If ReadyToTrip returns true, the CircuitBreaker will be placed into the open state. If ReadyToTrip is nil, default ReadyToTrip is used. Default ReadyToTrip returns true when the number of consecutive failures is more than 5.
OnStateChange is called whenever the state of the CircuitBreaker changes.
IsSuccessful is called with the error returned from a request. If IsSuccessful returns true, the error is counted as a success. Otherwise the error is counted as a failure. If IsSuccessful is nil, default IsSuccessful is used, which returns false for all non-nil errors.
type Signer ¶ added in v1.0.0
type Signer struct {
// contains filtered or unexported fields
}
type SingleFlightCall ¶ added in v0.6.0
type State ¶ added in v0.30.0
type State int
State is a type that represents a state of CircuitBreaker.
These constants are states of CircuitBreaker.
type StateFunc ¶ added in v0.82.0
type StateFunc[S comparable] func(pre S) S
type StateMachine ¶ added in v0.82.0
type StateMachine[S comparable] struct { // contains filtered or unexported fields }
func NewStateMachine ¶ added in v0.82.0
func NewStateMachine[S comparable](states []S) *StateMachine[S]
func NewStateMachineByMap ¶ added in v0.82.0
func NewStateMachineByMap[S comparable](m map[S]StateFunc[S]) *StateMachine[S]
func (*StateMachine[S]) Run ¶ added in v0.82.0
func (m *StateMachine[S]) Run(s S) S
func (*StateMachine[S]) WithFunc ¶ added in v0.82.0
func (m *StateMachine[S]) WithFunc(s S, f StateFunc[S])
type Struct ¶ added in v0.9.0
type Struct struct { Name string // 名字 Comment string // 注释 Description string // 描述 Type reflect.Type // 反射类型 Fields []Field // 结构体字段 }
func MakeStruct ¶ added in v0.9.0
func MakeStruct() Struct
func ResolveStruct ¶ added in v0.9.0
func ResolveStructSlice ¶ added in v1.5.0
type StructCommentEntity ¶ added in v0.9.0
type TimeTracer ¶ added in v0.13.0
type TimeTracer struct {
// contains filtered or unexported fields
}
func (*TimeTracer) Begin ¶ added in v0.13.0
func (impl *TimeTracer) Begin()
func (*TimeTracer) New ¶ added in v0.13.0
func (impl *TimeTracer) New(pctx ProxyContext, extras ...any) Tracer
func (*TimeTracer) Stop ¶ added in v0.13.0
func (impl *TimeTracer) Stop(_ ...any)
type TimestampTypeCtxHelper ¶ added in v1.23.0
type TimestampTypeCtxHelper = ContextHelper[TimestampType, int64]
type Token ¶ added in v0.57.0
type Token[T any] struct { // contains filtered or unexported fields }
type Tracer ¶ added in v0.13.0
type Tracer interface { New(pctx ProxyContext, extras ...any) Tracer // 新建Tracer,每个方法调用均新建一个 Begin() Stop(args ...any) }
type TreeEntity ¶ added in v0.74.0
type TwoStepCircuitBreaker ¶ added in v0.30.0
type TwoStepCircuitBreaker[P, R any] struct { // contains filtered or unexported fields }
TwoStepCircuitBreaker is like CircuitBreaker but instead of surrounding a function with the breaker functionality, it only checks whether a request can proceed and expects the caller to report the outcome in a separate step using a callback.
func NewTwoStepCircuitBreaker ¶ added in v0.30.0
func NewTwoStepCircuitBreaker[P, R any](st Settings) *TwoStepCircuitBreaker[P, R]
NewTwoStepCircuitBreaker returns a new TwoStepCircuitBreaker configured with the given Settings.
func (*TwoStepCircuitBreaker[P, R]) Allow ¶ added in v0.30.0
func (tscb *TwoStepCircuitBreaker[P, R]) Allow() (done func(success bool), err error)
Allow checks if a new request can proceed. It returns a callback that should be used to register the success or failure in a separate step. If the circuit breaker doesn't allow requests, it returns an error.
func (*TwoStepCircuitBreaker[P, R]) Counts ¶ added in v0.30.0
func (tscb *TwoStepCircuitBreaker[P, R]) Counts() Counts
Counts returns internal counters
func (*TwoStepCircuitBreaker[P, R]) Name ¶ added in v0.30.0
func (tscb *TwoStepCircuitBreaker[P, R]) Name() string
Name returns the name of the TwoStepCircuitBreaker.
func (*TwoStepCircuitBreaker[P, R]) State ¶ added in v0.30.0
func (tscb *TwoStepCircuitBreaker[P, R]) State() State
State returns the current state of the TwoStepCircuitBreaker.
type UserKeyTypeCtxHelper ¶ added in v1.23.0
type UserKeyTypeCtxHelper = ContextHelper[UserKeyType, uint64]
Source Files ¶
- aop.go
- as.go
- assert.go
- basetype.go
- batch.go
- bit.go
- breaker.go
- comparable.go
- context.go
- copy.go
- crypto.go
- db_batch.go
- db_entity.go
- db_find.go
- db_result.go
- db_wrap.go
- dimension.go
- enum.go
- equal.go
- error.go
- escape.go
- event.go
- field_column.go
- field_cond.go
- file.go
- format_state.go
- func_name.go
- go.go
- http.go
- http_body.go
- http_client.go
- http_param.go
- http_proxy.go
- inject.go
- ip.go
- is.go
- join.go
- jwt.go
- keyvalue.go
- logic.go
- logic_run.go
- map.go
- math.go
- must.go
- nameof.go
- number.go
- or.go
- parse_struct.go
- ptr.go
- retry.go
- router.go
- signature.go
- singleflight.go
- slice.go
- state_machine.go
- str.go
- str2bytes.go
- structconv.go
- tcp_proxy.go
- time.go
- timeout.go
- unique.go
- url.go
- valueof.go
- worker.go