do

package module
v0.40.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2023 License: MIT Imports: 25 Imported by: 4

README

do

GoDoc Go Report Card

Do something interesting.

Base Go1.18 with generic.

Must

Panic if error is not nil, otherwise return some result except the error.

package main

import (
	"fmt"

	"github.com/donnol/do"
)

func main() {
	do.Must(retErr()) // without result

	// specify result type with type parameter
	_ = do.Must1(retErrAndOneResult()) // with one result

	_, _ = do.Must2(retErrAndTwoResult()) // with two result
}

func retErr() error {
	return fmt.Errorf("a new error")
}

func retErrAndOneResult() (int, error) {
	return 1, fmt.Errorf("a new error")
}

func retErrAndTwoResult() (int, int, error) {
	return 0, 1, fmt.Errorf("a new error")
}

Slice to map by key

r := KeyValueBy([]string{"a", "aa", "aaa"}, func(str string) (string, int) {
	return str, len(str)
})
want := map[string]int{"a": 1, "aa": 2, "aaa": 3}
// r is what we want.

Join

r := NestedJoin([]Book{
	{Id: 1, Title: "hello", Author: 1},
	{Id: 2, Title: "world", Author: 1},
	{Id: 3, Title: "good", Author: 2},
	{Id: 4, Title: "job", Author: 2},
}, []User{
	{Id: 1, Name: "jd"},
	{Id: 2, Name: "jc"},
}, UserBookMatcher, func(j Book, k User) BookWithUser {
	return BookWithUser{
		Book:     j,
		UserName: k.Name,
	}
})
want := []BookWithUser{
	{Book{1, "hello", 1}, "jd"},
	{Book{2, "world", 1}, "jd"},
	{Book{3, "good", 2}, "jc"},
	{Book{4, "job", 2}, "jc"},
}
// r is what we want.
r := HashJoin([]Book{
	{Id: 1, Title: "hello", Author: 1},
	{Id: 2, Title: "world", Author: 1},
	{Id: 3, Title: "good", Author: 2},
	{Id: 4, Title: "job", Author: 2},
}, []User{
	{Id: 1, Name: "jd"},
	{Id: 2, Name: "jc"},
}, func(item Book) uint64 {
	return item.Author
}, func(item User) uint64 {
	return item.Id
}, func(j Book, k User) BookWithUser {
	return BookWithUser{
		Book:     j,
		UserName: k.Name,
	}
})
want := []BookWithUser{
	{Book{1, "hello", 1}, "jd"},
	{Book{2, "world", 1}, "jd"},
	{Book{3, "good", 2}, "jc"},
	{Book{4, "job", 2}, "jc"},
}
// r is what we want.

Send HTTP request

Send a http request with a simple function.

Worker

A worker pool process job with a limited number Goroutine.

DB connect and find

// 0. open a db
var tdb *sql.DB

// 1. define a finder
type finderOfUser struct {
	id uint64
}

func (f *finderOfUser) Query() (query string, args []any) {
	query = `select * from user where id = ?`
	args = append(args, f.id)
	return
}

func (f *finderOfUser) NewScanObjAndFields(colTypes []*sql.ColumnType) (r *UserForDB, fields []any) {
	r = &UserForDB{}
	fields = append(fields,
		&r.Id,
		&r.Name,
	)
	return
}

// 2. find
finder := &finderOfUser{
	id: 1,
}
r, err := do.FindAll(tdb, finder, (UserForDB{}))
if err != nil {
	panic(err)
}

// 3. find per batch
finder := &finderOfUser{
	id: 1,
}
// batchNum is 10, if there are 20 records, it will be processed in two parts
err := do.Batch(tdb, finder, 10, func(r []UserForDB) error {
	// Process this batch of data

	return nil
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
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")
)
View Source
var (
	ErrWorkerIsStop = errors.New("Worker is stop")
	ErrNilJobDo     = errors.New("Job do field is nil")
)
View Source
var (
	ErrNilDoer = errors.New("f is nil")
)

Functions

func As added in v0.8.0

func As[T any](v any) T

As assert the value v to type T

func AsOk added in v0.27.0

func AsOk[T any](v any) (T, bool)

func Assert added in v0.33.0

func Assert[T comparable](handler AssertHandler, l, r 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 BatchRun added in v0.36.0

func BatchRun[T any](s []T, batchNum int, handler func([]T) error) (err error)

BatchRun handle data per batch

func BytesToString added in v0.5.0

func BytesToString(b []byte) string

BytesToString converts byte slice to string without a memory allocation.

func CodeIs200 added in v0.2.0

func CodeIs200(code int) error

func DayZero added in v0.18.0

func DayZero(t time.Time) time.Time

func Equal added in v0.33.0

func Equal[T comparable](l, r T) bool

func EventLoop added in v0.25.0

func EventLoop[I, O, R any](ctx C, n int) (chan<- EventEntity[I, O, R], chan<- struct{})

func ExecWithBatch added in v0.35.0

func ExecWithBatch[S Storer, Q Queryer](db S, batch []Q) (ra, lid int64, err error)

ExecWithBatch exec with batch

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 FindAll added in v0.2.0

func FindAll[S Storer, F Finder[R], R any](db S, finder F, initial R) (r []R, err error)

func FindFirst added in v0.2.0

func FindFirst[S Storer, F Finder[R], R any](db S, finder F, res *R) (err error)

func FindFirstByFunc added in v0.16.0

func FindFirstByFunc[S Storer, F FindFunc[R], R any](db S, finder F, res *R) (err error)

func FindList added in v0.2.0

func FindList[S Storer, F Finder[R], R any](db S, finder F, res *[]R) (err error)

func FindListByFunc added in v0.16.0

func FindListByFunc[S Storer, F FindFunc[R], R any](db S, finder F, res *[]R) (err error)

func FindOne added in v0.2.0

func FindOne[S Storer, F Finder[R], R any](db S, finder F, initial R) (r R, err error)

func FindWithBatch added in v0.35.0

func FindWithBatch[S Storer, B Batcher[R], R any](db S, batcher B, res *[]R) (err error)

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 ForgotKey added in v0.6.0

func ForgotKey(key string)

func FuncName added in v0.2.0

func FuncName(skip int, withFileInfo bool) string

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 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 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

func IsExpired(deadline, now time.Time) bool

IsExpired show if deadline is expired compared to now always return false if deadline is zero

func IsValidIP added in v0.28.0

func IsValidIP(ip string) bool

IsValidIP check the ip if is a valid ipv4 or ipv6 addr.

func IsZero added in v0.12.0

func IsZero[T comparable](v T) bool

func JSONExtractor added in v0.2.0

func JSONExtractor[R any](data []byte) (R, error)

func JoinUint added in v0.40.0

func JoinUint(parts []uint64) (n uint64)

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 Keys added in v0.8.0

func Keys[K comparable, E any](collection map[K]E) []K

func Log added in v0.32.0

func Log(err error)

Log log the err if err is not nill and continue

func Log1 added in v0.32.0

func Log1[T any](a1 T, err error) T

Log1 log the err if err is not nill,and continue with 1 result

func Log2 added in v0.32.0

func Log2[T1, T2 any](a1 T1, a2 T2, err error) (T1, T2)

Log2 log the err if err is not nill,and continue with 2 result

func Log3 added in v0.32.0

func Log3[T1, T2, T3 any](a1 T1, a2 T2, a3 T3, err error) (T1, T2, T3)

Log3 log the err if err is not nill,and continue with 3 result

func Log4 added in v0.32.0

func Log4[T1, T2, T3, T4 any](a1 T1, a2 T2, a3 T3, a4 T4, err error) (T1, T2, T3, T4)

Log4 log the err if err is not nill,and continue with 4 result

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 MatchError

func MatchError(v any) bool

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 MkdirAllIfNotExist(dir string) error

func MonthFirst added in v0.18.0

func MonthFirst(t time.Time) time.Time

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 Must

func Must(err error)

Must panic if err is not nill

func Must1

func Must1[T any](a1 T, err error) T

Must1 panic if err is not nill,or return 1 result

func Must2

func Must2[T1, T2 any](a1 T1, a2 T2, err error) (T1, T2)

Must2 panic if err is not nill,or return 2 result

func Must3

func Must3[T1, T2, T3 any](a1 T1, a2 T2, a3 T3, err error) (T1, T2, T3)

Must3 panic if err is not nill,or return 3 result

func Must4

func Must4[T1, T2, T3, T4 any](a1 T1, a2 T2, a3 T3, a4 T4, err error) (T1, T2, T3, T4)

Must4 panic if err is not nill,or return 4 result

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 NewError

func NewError[T any](inner T) error

func ParseTime added in v0.18.0

func ParseTime(t string, layouts ...string) (r time.Time, err error)

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 Pow10 added in v0.40.0

func Pow10(n int) (r uint64)

Pow10 10^n, return 0 if n < 0

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())

ProxyTraceBegin LIFO

func PtrTo added in v0.27.0

func PtrTo[T any](v T) *T

PtrTo [deprecate] return pointer of a new value copied from v

func RawExtractor added in v0.25.0

func RawExtractor(data []byte) ([]byte, error)

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

func RetryWithDeadline(ctx context.Context, d time.Time, f Doer) error

RetryWithDeadline retry f before d exceeds if f failed

func RetryWithTimes added in v0.5.0

func RetryWithTimes(ctx context.Context, tryTimes int, f Doer) error

RetryWithTimes retry f tryTimes times if f failed

func SQLProcess added in v0.17.0

func SQLProcess(funcs ...SQLQueryFunc) (query SQLQuery, args SQLArgs)

SQLProcess process sql and args one by one, add more parts based on first sql

func SQLProcessRaw added in v0.17.1

func SQLProcessRaw(funcs ...SQLQueryFunc) (query string, args []any)

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 SplitUint added in v0.40.0

func SplitUint(n uint64) []uint64

SplitUint 0 -> [0], [1234] -> [1, 2, 3, 4]

func StreamRun added in v0.36.0

func StreamRun[T any](s chan T, batchNum int, handler func([]T) error) (err error)

StreamRun handle data by stream, if batchNum is >0, run with batch

func StringToBytes added in v0.5.0

func StringToBytes(s string) []byte

StringToBytes converts string to byte slice without a memory allocation.

func TCPProxy added in v0.19.0

func TCPProxy(localAddr, remoteAddr string, handlers ...func(lconn, rconn net.Conn)) (err error)

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 TCPProxyDefaultHandler(lconn, rconn net.Conn)

func TCPRecv added in v0.19.0

func TCPRecv(localAddr string, handler func(conn net.Conn)) (err error)

TCPRecv recv from local addr with handler, it will block on (*net.TCPListener).Accept

func TCPSend added in v0.19.0

func TCPSend(remoteAddr string, handler func(conn net.Conn) error) (err error)

TCPSend send to remote addr with handler

func ThisMonthFirst added in v0.12.0

func ThisMonthFirst() time.Time

func ThisYearFirst added in v0.12.0

func ThisYearFirst() time.Time

func TodayZero added in v0.12.0

func TodayZero() time.Time

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 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 WrapDB added in v0.2.0

func WrapDB(
	ctx context.Context,
	driverName string,
	dataSourceName string,
	f func(
		ctx context.Context,
		conn *sql.DB,
	) error,
) error

func WrapSQLConn added in v0.2.0

func WrapSQLConn(
	ctx context.Context,
	db *sql.DB,
	f func(
		ctx context.Context,
		conn *sql.Conn,
	) error,
) error

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 WrapTx added in v0.2.0

func WrapTx(
	ctx context.Context,
	db *sql.DB,
	f func(
		ctx context.Context,
		tx *sql.Tx,
	) error,
) (err error)

func WrapTxFindAll added in v0.2.0

func WrapTxFindAll[F Finder[R], R any](
	ctx context.Context,
	db *sql.DB,
	finder F,
	initial R,
) (r []R, err error)

func XMLExtractor added in v0.2.0

func XMLExtractor[R any](data []byte) (R, error)

func YearFirst added in v0.18.0

func YearFirst(t time.Time) time.Time

func Zero added in v0.27.0

func Zero[T any]() T

Types

type AssertHandler added in v0.33.0

type AssertHandler interface {
	Errorf(format string, args ...any)
}

type Batcher added in v0.35.0

type Batcher[T any] interface {
	Batch() []Finder[T]
}

type C added in v0.24.0

type C = context.Context

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 CodeChecker func(code int) error

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)

func (ContextHelper[K, V]) Value added in v0.37.0

func (h ContextHelper[K, V]) Value(ctx context.Context) (v V, ok bool)

func (ContextHelper[K, V]) WithValue added in v0.37.0

func (h ContextHelper[K, V]) WithValue(ctx context.Context, v V) context.Context

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 DecodeFunc added in v0.28.0

type DecodeFunc[T ParamData] func(src T, v any) error

func (DecodeFunc[T]) Decode added in v0.28.0

func (f DecodeFunc[T]) Decode(src T, v any) error

type Decoder added in v0.28.0

type Decoder[T ParamData] interface {
	Decode(src T, v any) error
}

type DoWithCtx added in v0.2.0

type DoWithCtx func(ctx context.Context) error

type Doer added in v0.5.0

type Doer = func(context.Context) (canRetry bool, err error)

type E added in v0.24.0

type E = error

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 Error

type Error[T any] struct {
	// contains filtered or unexported fields
}

Error is a error type with any element

func ConvertError

func ConvertError(v any) (*Error[*e], bool)

func (Error[T]) Error

func (e Error[T]) Error() string

func (Error[T]) Inner

func (e Error[T]) Inner() T

type ErrorHandler added in v0.2.0

type ErrorHandler func(error)

type EventEntity added in v0.25.0

type EventEntity[I, O, R any] struct {
	Param   I
	Do      PipeFunc[I, O]
	Success PipeFunc[O, R]
	Failed  PipeFunc[E, R]

	Handler func(R, E)
}

type EventFunc added in v0.25.0

type EventFunc[I, O, R any] func(
	ctx C,
	param I,
	do PipeFunc[I, O],
	success PipeFunc[O, R],
	failed PipeFunc[E, R],
) (r R, err E)

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 (FindFunc[R]) NewScanObjAndFields added in v0.16.0

func (f FindFunc[R]) NewScanObjAndFields(colTypes []*sql.ColumnType) (r *R, fields []any)

func (FindFunc[R]) Query added in v0.16.0

func (f FindFunc[R]) Query() (query string, args []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 HTTPProxyOption added in v0.27.0

type HTTPProxyOption struct {
	Director       func(req *http.Request)
	ModifyResponse func(r *http.Response) error
	ErrorHandler   func(w http.ResponseWriter, r *http.Request, err error)
}

type Ioc added in v0.29.0

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

Ioc Inversion of Control, dependency inject

func NewIoc added in v0.29.0

func NewIoc(
	opt *IocOption,
) *Ioc

func (*Ioc) Inject added in v0.29.0

func (ioc *Ioc) Inject(v any) (err error)

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

func (ioc *Ioc) RegisterProvider(v any) (err error)

RegisterProvider register provider,like `func New(fielda TypeA, fieldb TypeB) (T)`

type IocOption added in v0.29.0

type IocOption struct {
	EnableUnexportedFieldSetValue bool // set value to unexported field
	Print                         bool // print inject procedure
}

type Job added in v0.2.0

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

func NewJob added in v0.2.0

func NewJob(do DoWithCtx, timeout time.Duration, eh ErrorHandler) *Job

type KeyOption added in v0.11.0

type KeyOption struct {
	Timeout time.Duration // key will expire when timeout
}

type Map added in v0.6.0

type Map[K comparable, T any] struct {
	// contains filtered or unexported fields
}

func NewMap added in v0.6.0

func NewMap[K comparable, T any](size ...int) *Map[K, T]

func (*Map[K, T]) Get added in v0.6.0

func (m *Map[K, T]) Get(key K) (value T)

func (*Map[K, T]) Insert added in v0.6.0

func (m *Map[K, T]) Insert(key K, value T, opts ...*KeyOption)

func (*Map[K, T]) Lookup added in v0.6.0

func (m *Map[K, T]) Lookup(key K) (value T, ok bool)

func (*Map[K, T]) Range added in v0.6.0

func (m *Map[K, T]) Range(f func(key K, value T))

func (*Map[K, T]) Remove added in v0.6.0

func (m *Map[K, T]) Remove(key K)

type ParamData added in v0.28.0

type ParamData interface {
	url.Values | []byte
}

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 PipeFunc added in v0.24.0

type PipeFunc[I, O any] func(C, I) (O, E)

type ProxyContext added in v0.13.0

type ProxyContext struct {
	PkgPath       string
	InterfaceName string
	MethodName    string
}

每个包、每个接口、每个方法唯一对应一个方法

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 Queryer added in v0.35.0

type Queryer interface {
	// return query sql and args
	Query() (query string, args []any)
}

type RespHeaderExtractor added in v0.21.0

type RespHeaderExtractor interface {
	Extract(h http.Header)
}

type ResultExtractor added in v0.2.0

type ResultExtractor[R any] func(data []byte) (R, error)

type RouteHandler added in v0.34.0

type RouteHandler[P, R any] interface {
	Parse(req *http.Request, p *P) error
	Write(w http.ResponseWriter, r R, err error)
}

type RouteRegister added in v0.34.0

type RouteRegister interface {
	Handle(method, path string, handlers http.HandlerFunc)
}

type SQLArgs added in v0.17.0

type SQLArgs []any

func (SQLArgs) Append added in v0.17.0

func (a SQLArgs) Append(s SQLArgs) SQLArgs

func (SQLArgs) Raw added in v0.17.0

func (a SQLArgs) Raw() []any

type SQLQuery added in v0.17.0

type SQLQuery string

func (SQLQuery) Append added in v0.17.0

func (q SQLQuery) Append(ss ...SQLQuery) (r SQLQuery)

Append add sql to query, if the q is a format string of fmt, fmt.Sprintf will be used to concat the sql; the q will be the format, the left sql will be arguments.

func (SQLQuery) Raw added in v0.17.0

func (q SQLQuery) Raw() string

type SQLQueryFunc added in v0.17.0

type SQLQueryFunc func() (query SQLQuery, args SQLArgs)

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 SingleFlightCall added in v0.6.0

type SingleFlightCall[R any] func() (R, error)

type Slice added in v0.6.0

type Slice[T any] struct {
	// contains filtered or unexported fields
}

func NewSlice added in v0.6.0

func NewSlice[T any](lenAndCap ...int) *Slice[T]

func (*Slice[T]) Append added in v0.6.0

func (s *Slice[T]) Append(values ...T)

func (*Slice[T]) Index added in v0.6.0

func (s *Slice[T]) Index(i int) T

func (*Slice[T]) Range added in v0.6.0

func (s *Slice[T]) Range(f func(item T, index int))

func (*Slice[T]) Reset added in v0.6.0

func (s *Slice[T]) Reset(lenAndCap ...int)

type State added in v0.30.0

type State int

State is a type that represents a state of CircuitBreaker.

const (
	StateClosed State = iota
	StateHalfOpen
	StateOpen
)

These constants are states of CircuitBreaker.

func (State) String added in v0.30.0

func (s State) String() string

String implements stringer interface.

type Storer added in v0.2.0

type Storer interface {
	*sql.DB | *sql.Tx | *sql.Conn
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

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 ResolveStruct(value any) (Struct, error)

func (Struct) GetFields added in v0.9.0

func (s Struct) GetFields() []Field

GetFields return all field in struct, include anonymous fields

type StructCommentEntity added in v0.9.0

type StructCommentEntity struct {
	StructName    string
	StructComment map[string]string
	FieldComment  map[string]string
}

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()

type TraceId added in v0.26.0

type TraceId string

type TraceKey added in v0.22.0

type TraceKey struct{}

type Tracer added in v0.13.0

type Tracer interface {
	New(pctx ProxyContext, extras ...any) Tracer // 新建Tracer,每个方法调用均新建一个
	Begin()
	Stop()
}

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 Worker added in v0.2.0

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

func NewWorker added in v0.2.0

func NewWorker(n int) *Worker

NewWorker new a worker with limit number

func (*Worker) Push added in v0.2.0

func (w *Worker) Push(job Job) error

func (*Worker) Start added in v0.2.0

func (w *Worker) Start()

func (*Worker) Stop added in v0.2.0

func (w *Worker) Stop()

Directories

Path Synopsis
cmd
letgo Module

Jump to

Keyboard shortcuts

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