Categorygithub.com/donnol/do
modulepackage
1.23.0
Repository: https://github.com/donnol/do.git
Documentation: pkg.go.dev

# README

do

GoDoc Go Report Card

Do something interesting.

Base Go1.18 with generic.

Usage of letgo

  • TCP代理
  • 从SQL建表语句生成结构体
  • 从接口定义生成Mock结构体

Install: go install github.com/donnol/do/cmd/letgo@latest

Usage:

NAME:
   letgo.exe - A new cli application

USAGE:
   letgo.exe [global options] command [command options] [arguments...]

COMMANDS:
   proxy       letgo proxy --localAddr=':54388' --remoteAddr='127.0.0.1:54399'
   sql2struct  letgo sql2struct 'create table user(id int not null)'
   mock        letgo mock -p=github.com/xxx/yyy -r
   help, h     Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --help, -h  show help

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
}

# Packages

No description provided by the author
No description provided by the author

# Functions

AgeByBirth get age and unit by birthday.
As assert the value v to type T.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Batch process data find from Storer in batches.
BatchConcurrent batch process data concurrently.
BatchRun handle data per batch.
BatchRunR handle data per batch.
BinPow return a**b with binary pow.
BinPow return a**b with binary pow.
BytesToString converts byte slice to string without a memory allocation.
CallInDefRec run f with defer recover to catch panic.
CallInDefRec2 run f with defer recover to catch panic.
No description provided by the author
No description provided by the author
ConvByName fill 'to' struct with 'from' by name like to.Name = from.Name to must be a struct pointer.
No description provided by the author
ConvSliceByName fill 'to' struct slice with 'from' by name.
Copy return a copy of v's value without deep copy.
No description provided by the author
No description provided by the author
No description provided by the author
Copy creates a deep copy of whatever is passed to it and returns the copy in an interface{}.
No description provided by the author
EscapeStruct escape struct field value with escaper, v must be a struct pointer.
Event do something with input I, handle result with success or failed.
No description provided by the author
ExecWithBatch exec with batch.
Factorial n <= 20, it will return 0 if n > 20, use FactorialBig instead.
FactorialBig n > 20.
FieldsByColumnType t is a struct pointer, and use it's field match column name to receive scan value.
FieldWithAlias use alias if not empty, or use defaultAlias.
No description provided by the author
No description provided by the author
No description provided by the author
FindFuncHelper return FindFunc with T.
No description provided by the author
No description provided by the author
No description provided by the author
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.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Go run f in a new goroutine with defer recover.
GoR run f in a new goroutine with defer recover, and return a chan of R.
HandleResult check affected rows first, if it is not zero then get last insert id.
HashJoin like hash join.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
HTTPProxy listen localAddr and transfer any request to remoteAddr.
No description provided by the author
Ignore1 ignore the last variable,and continue with 1 result.
Ignore2 ignore the last variable,and continue with 2 result.
Ignore3 ignore the last variable,and continue with 3 result.
Ignore4 ignore the last variable,and continue with 4 result.
Ignore5 ignore the last variable,and continue with 5 result.
No description provided by the author
No description provided by the author
No description provided by the author
IsComparable check if a type is comparable in compile time.
IsExpired show if deadline is expired compared to now always return false if deadline is zero.
No description provided by the author
No description provided by the author
IsValidIP check the ip if is a valid ipv4 or ipv6 addr.
No description provided by the author
No description provided by the author
No description provided by the author
KeyBy slice to map, key specified by iteratee, value is slice element.
No description provided by the author
KeyValueBy slice to map, key value specified by iteratee.
KeyValueGroupBy []int{{id: 1, from: gd}, {id: 2, from: gd}} -> map[string][]int{gd: []int{1, 2}}.
No description provided by the author
No description provided by the author
Log log the err if err is not nill and continue.
Log1 log the err if err is not nill,and continue with 1 result.
Log2 log the err if err is not nill,and continue with 2 result.
Log3 log the err if err is not nill,and continue with 3 result.
Log4 log the err if err is not nill,and continue with 4 result.
Log5 log the err if err is not nill,and continue with 5 result.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
MergeKeyValue merge m2 into m1, will override m1 key value if both exists.
No description provided by the author
No description provided by the author
MultipartBody new a multipart writer with body, mark with fieldname and name, write data to it.
Must panic if err is not nill.
Must1 panic if err is not nill,or return 1 result.
Must2 panic if err is not nill,or return 2 result.
Must3 panic if err is not nill,or return 3 result.
Must4 panic if err is not nill,or return 4 result.
Must5 panic if err is not nill,or return 5 result.
NestedJoin like nested loop join.
No description provided by the author
NewCircuitBreaker returns a new CircuitBreaker configured with the given Settings.
NewCrypto NewCrypto key: 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewSigner which secret is base64 encoded secret can use `ssh-keygen -t rsa -b 2048 -m PKCS8 -f jwtRS256.key` to generate, it will generate `jwtRS256.key` and `jwtRS256.key.pub`, and the first file is what we want.
No description provided by the author
No description provided by the author
No description provided by the author
NewTwoStepCircuitBreaker returns a new TwoStepCircuitBreaker configured with the given Settings.
NewWorker new a worker with limit number.
ObjectAndFieldsHelper if *T is interface{ ValuePtrs() []any } then use its results as fields, otherwise use reflect to get fields by ColumnType.
Or returns the first of its arguments that is not equal to the zero value.
No description provided by the author
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.
Pipe is a pipe run the PipeFuncs in order.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Pointer return a pointer of type T.
Pow10 10^n, return 0 if n < 0.
No description provided by the author
ProxyTraceBegin LIFO.
No description provided by the author
No description provided by the author
RegisterProxyMethod 注册代理方法,根据包名+接口名+方法名唯一对应一个方法;在有了泛型后还要加上类型参数,唯一键变为包名+接口名+方法名+TP1,TP2,...
No description provided by the author
RegisterRouter register router to RouteRegister with http.HandlerFunc.
ReplaceIP replace link 's ip with nip.
No description provided by the author
No description provided by the author
RetryWithDeadline retry f before d exceeds if f failed.
RetryWithTimes retry f tryTimes times if f failed.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
RunWithTimeout run func with timeout, return even if the func haven't completed.
SendHTTPRequest send http request and get result of type R.
SingleFlight make sure only one request is doing with one key.
SplitUint 0 -> [0], [1234] -> [1, 2, 3, 4].
No description provided by the author
StreamRun handle data by stream, if batchNum is >0, run with batch.
StreamRunR handle data by stream, if batchNum is >0, run with batch.
StringToBytes converts string to byte slice without a memory allocation.
No description provided by the author
TCPProxy listen localAddr and transfer any request to remoteAddr.We can use handlers to specify one custom func to transfer data.
No description provided by the author
TCPRecv recv from local addr with handler, it will block on (*net.TCPListener).Accept.
TCPSend send to remote addr with handler.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ValueAs get value by key from *Map[K, any], and assert value type to T.
ValueOf return v.field's value, if v is a struct or map.
No description provided by the author
WithWhere return condition if t is not a zero value of T.
WrapConnFindAll query by stmt and args, return values with dest support many rows.
No description provided by the author
No description provided by the author
No description provided by the author
WrapSQLQueryRows query by stmt and args, return values with dest only support one row.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Constants

No description provided by the author
No description provided by the author
These constants are states of CircuitBreaker.
These constants are states of CircuitBreaker.
These constants are states of CircuitBreaker.

# Variables

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
ErrOpenState is returned when the CB state is open.
ErrTooManyRequests is returned when the CB state is half open and the requests count is over the cb maxRequests.
No description provided by the author
东八,Asia/Shanghai.
No description provided by the author

# Structs

No description provided by the author
No description provided by the author
CircuitBreaker is a state machine to prevent sending requests that are likely to fail.
No description provided by the author
No description provided by the author
Counts holds the numbers of requests and their successes/failures.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
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 }.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Ioc Inversion of Control, dependency inject.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
每个包、每个接口、每个方法唯一对应一个方法.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Settings configures CircuitBreaker: Name is the name of the CircuitBreaker.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
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.
No description provided by the author
No description provided by the author

# Interfaces

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Interface for delegating copy process to type.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
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.
No description provided by the author
No description provided by the author
Id to/from string when json encode/decode.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
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).
No description provided by the author
No description provided by the author
No description provided by the author
State is a type that represents a state of CircuitBreaker.
No description provided by the author
No description provided by the author