Documentation ¶
Overview ¶
Example (IntHeap) ¶
This example inserts several ints into an IntHeap, checks the minimum, and removes them in order of priority.
package main import ( "fmt" "github.com/researchlab/gdk" ) // An IntHeap is a min-heap of ints type IntHeap []int func main() { h := gdk.NewHeap(IntHeap{2, 1, 5}, func(i1, i2 int) int { return i1 - i2 }) h.Push(3) for h.Len() > 0 { fmt.Printf("%d ", h.Pop()) } }
Output: 1 2 3 5
Index ¶
- Constants
- Variables
- func ArrayContains[E string | int64 | int | float64](array []E, key E) bool
- func ArrayMax[E Ordered](array ...E) E
- func ArrayMerge[E string | int64 | int](arraya, arrayb []E, arrays ...[]E) (array []E)
- func ArrayMin[E Ordered](array ...E) E
- func ArraySum[E int64 | int | float64](array []E) (sum E)
- func ArrayToMap[E, R, T any](array []E, f TFunc[E, R, T]) (out map[any]T)
- func ArrayUnique[E int64 | int | string](in []E) (out []E)
- func BytesToFloat64(bytes []byte) (data float64, err error)
- func BytesToReadable(bytes float64, precision ...int) string
- func Create(name string) (*os.File, error)
- func Dir(fp string) string
- func DirsUnder(dirPath string) ([]string, error)
- func EnsureDirRW(dataDir string) error
- func Ext(fp string) string
- func FileMTime(fp string) (int64, error)
- func FileSize(fp string) (int64, error)
- func FilesUnder(dirPath string) ([]string, error)
- func Float64Precision(f float64, precision int, round bool) float64
- func Float64ToBytes(input float64) []byte
- func Float64ToStr(num float64, precision int) string
- func HttpGet(ho *HttpOptions) (*http.Response, error)
- func HttpPostFiles(ho *HttpOptions) (*http.Response, error)
- func HttpPostForm(ho *HttpOptions) (*http.Response, error)
- func HttpPostJSON(ho *HttpOptions) (*http.Response, error)
- func InsureDir(fp string) error
- func IsEmail(email string) bool
- func IsEmailRFC(email string) bool
- func IsExist(fp string) bool
- func IsFile(fp string) bool
- func IsUrl(url string) bool
- func MapClear[K comparable, V any](data map[K]V)
- func MapFilter[K comparable, V any](data map[K]V, f BiFunc[bool, K, V]) map[K]V
- func MapKeys[K comparable, V any](data map[K]V) []K
- func MapRange[K comparable, V any](data map[K]V, f BiFunc[bool, K, V])
- func MapSize[K comparable, V any](data map[K]V) int
- func MapToStruct(obj map[string]interface{}, data interface{}) (interface{}, error)
- func MapValues[K comparable, V any](data map[K]V) []V
- func Name(fp string) string
- func RandomInts(start int, end int, count int) []int
- func ReadResponse(resp *http.Response) (bodyBytes []byte, isGzip bool, err error)
- func RealPath(fp string) (string, error)
- func Remove(name string) error
- func Rename(src string, target string) error
- func SearchFile(filename string, paths ...string) (fullPath string, err error)
- func SearchFileWithAffix(dirPath, prefix, suffix string) (fullPath string, exist bool)
- func SelfDir() string
- func SelfPath() string
- func SetGlobalErrorTemplates(templates map[any]string)
- func SetGlobalFields(fields map[string]interface{})
- func SetGlobalTag(tag string)
- func StrToFloat64(str string, precision int) float64
- func StrToFloat64Round(str string, precision int, round bool) float64
- func StringReverse(s string) (string, error)
- func StructToMap(obj interface{}) map[string]interface{}
- func ToInt64(value interface{}) (d int64, err error)
- func UnsetGlobals(options ...string)
- type BiFunc
- type CMP
- type Comparable
- type Complex
- type EQL
- type Err
- type ErrDetail
- type FileUploadInfo
- type Float
- type Func
- type Functions
- type Heap
- type HttpOptions
- type Info
- type Integer
- type Ordered
- type Signed
- type Stack
- type TFunc
- type Unsigned
Examples ¶
Constants ¶
const ( G_TAG = "globalTag" G_FIELDS = "globalFields" G_ERROR_TEMPLATES = "globalErrorTemplates" )
const ( FORM_MULTIPART = "multipart/form-data" FORM_ENCODED = "application/x-www-form-urlencoded" APPLICATION_JSON = "application/json" CONTENT_TYPE = "Content-Type" )
const ( ERR_PARAMS_INVALID = 11111 ERR_OPEN_FILE_FAILED = 11112 ERR_WRITER_FAILED = 11113 ERR_WRITE_FIELD_FAILED = 11114 ERR_WRITER_CLOSE_FAILED = 11115 ERR_UNKOWN_TYPE = 11116 )
Variables ¶
var ERR_BYTES_INVALILD = errors.New("BytesToFloat64 bytes invalid")
ERR_BYTES_INVALILD
var ERR_NEED_NUMERIC = errors.New("ToInt64 need numeric")
ERR_NEED_NUMERIC
var ( // ErrParamsNotAdapted params length invalid ErrParamsNotAdapted = errors.New("The number of params is not adapted.") )
Functions ¶
func ArrayContains ¶ added in v0.1.2
ArrayContains return true if this array contains the specified element.
func ArrayMerge ¶
ArrayMerge merge two or more arrays into a new array
func ArrayMin ¶ added in v0.1.2
func ArrayMin[E Ordered](array ...E) E
ArrayMin return the smaller one
func ArrayToMap ¶ added in v0.1.3
ArrayToMap mapping the given array to a map[r]t
func ArrayUnique ¶
ArrayUnique remove Duplicate item of the given array
func BytesToFloat64 ¶
BytesToFloat64 convert bytes to float64
func BytesToReadable ¶
BytesToReadable convert bytes to human readable string KB,MB,GB,TB,PB,EB,ZB,YB
func EnsureDirRW ¶
EnsureDirRW ensure the datadir and make sure it's rw-able
func Ext ¶
Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final slash-separated element of path; it is empty if there is no dot.
func FilesUnder ¶
FilesUnder list files under dirPath
func Float64Precision ¶
Float64Precision float指定精度; round为true时, 表示支持四舍五入
func Float64ToBytes ¶
Float64ToBytes convert float64 to bytes; []uint8
func Float64ToStr ¶
Float64ToStr convert float64 to string 支持指定精度
func HttpGet ¶ added in v0.1.2
func HttpGet(ho *HttpOptions) (*http.Response, error)
HttpGet request to target url
func HttpPostFiles ¶ added in v0.1.2
func HttpPostFiles(ho *HttpOptions) (*http.Response, error)
HttpPostFiles post files
func HttpPostForm ¶ added in v0.1.2
func HttpPostForm(ho *HttpOptions) (*http.Response, error)
HttpPostForm post form field value
func HttpPostJSON ¶ added in v0.1.2
func HttpPostJSON(ho *HttpOptions) (*http.Response, error)
HttpPostJSON post json format value to http server
func IsEmail ¶ added in v0.1.2
IsEmail validates string is an email address, if not return false basically validation can match 99% cases
func IsEmailRFC ¶ added in v0.1.2
IsEmailRFC validates string is an email address, if not return false this validation omits RFC 2822
func IsExist ¶
IsExist checks whether a file or directory exists It returns false when the file or directory does not exist.
func IsFile ¶
IsFile checks whether the path is a file, it returns false when it's a directory or does not exist.
func IsUrl ¶ added in v0.1.2
IsUrl validates string is a url link, if not return false simple validation can match 99% cases
func MapClear ¶ added in v0.1.2
func MapClear[K comparable, V any](data map[K]V)
MapClear remove all keys and values in map
func MapFilter ¶ added in v0.1.2
func MapFilter[K comparable, V any](data map[K]V, f BiFunc[bool, K, V]) map[K]V
MapFilter 过滤出符合条件的key,value
func MapKeys ¶ added in v0.1.2
func MapKeys[K comparable, V any](data map[K]V) []K
MapKeys return all key as slice in map
func MapRange ¶ added in v0.1.2
func MapRange[K comparable, V any](data map[K]V, f BiFunc[bool, K, V])
MapRange calls f sequentially for each key and value present in the map.
func MapSize ¶ added in v0.1.2
func MapSize[K comparable, V any](data map[K]V) int
MapSize return count of size
func MapToStruct ¶
MapToStruct map obj to struct data
func MapValues ¶ added in v0.1.2
func MapValues[K comparable, V any](data map[K]V) []V
MapValues return all value as slice in map
func RandomInts ¶
RandomInts 生成count个[start,end)结束的不重复的随机数
func ReadResponse ¶ added in v0.1.2
ReadResponse return http.Response.body, isGzip=true if contentEncoding=gzip
func SearchFile ¶
Search a file in the give paths. this is often used in search config file in /etc ~/
func SearchFileWithAffix ¶
SearchFileWithAffix search file under dirPath and meet the followinng conditions match prefix and suffix prefix and suffix must been set and not be empty
func SetGlobalErrorTemplates ¶ added in v0.1.2
SetGlobalErrorTemplates cache error templates 建议做多设置一次
func SetGlobalFields ¶ added in v0.1.2
func SetGlobalFields(fields map[string]interface{})
SetGlobalFields global fields, set at most once 建议最多设置一次
func StrToFloat64 ¶
StrToFloat64 convert string to float64, supported the given precision
func StrToFloat64Round ¶
StrToFloat64Round convert string to float64, supported the given precision and round
func StringReverse ¶ added in v0.1.2
Reverse to reverse the string
func StructToMap ¶
func StructToMap(obj interface{}) map[string]interface{}
StructToMap struct convert to map
func UnsetGlobals ¶ added in v0.1.3
func UnsetGlobals(options ...string)
Types ¶
type Comparable ¶
Comparable is a interface to compare action
type Complex ¶
type Complex interface { ~complex64 | ~complex128 }
Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.
type Err ¶ added in v0.1.2
type Err interface { Is(any) bool WithTag(string) Err WithFields(map[string]interface{}) Err WithCode(any) Err Error() string Export() ErrDetail Detail() string DetailText() string }
func ErrorCause ¶ added in v0.1.2
ErrorCause error recorder
Example ¶
deal with the given error
package main import ( "encoding/json" "fmt" "github.com/researchlab/gdk" ) func jsonMarshal(size int) error { _, err := json.Marshal(make(chan struct{}, size)) if err != nil { return gdk.ErrorCause(err) } return nil } func main() { const ERR_MARSHAL_FAILED = 1000 var size = 10 var e gdk.Err err := jsonMarshal(size) if err != nil { e = gdk.ErrorCause(err).WithCode(ERR_MARSHAL_FAILED).WithTag("ParseError"). WithFields(map[string]interface{}{ "inputs": map[string]int{ "size": 10, }, }) } if e != nil { // e not equal nil } errTxt := e.DetailText() fmt.Println(errTxt) }
Output: CallChains=ExampleErrorCause.jsonMarshal, Tag=ParseError, Fields={"inputs":{"size":10}}, Code=1000, Error=json: unsupported type: chan struct {}
func ErrorT ¶ added in v0.1.2
ErrorT new error by error code and error template
Example ¶
use error Templates
package main import ( "fmt" "github.com/researchlab/gdk" ) func main() { const ( ERR_PARAMS_INVALID = "PARAMS INVALID" ) var errorTemplates = map[any]string{ ERR_PARAMS_INVALID: "params invalid, include(%v)", } gdk.SetGlobalErrorTemplates(errorTemplates) gdk.SetGlobalTag("ip:192.168.190.70") gdk.SetGlobalFields(map[string]interface{}{ "service": "timer-job-3", }) defer gdk.UnsetGlobals() err := gdk.ErrorT(ERR_PARAMS_INVALID, "size need > 5, code need > 0") fmt.Println(err.DetailText()) }
Output: CallChains=ExampleErrorT, GlobalTag=ip:192.168.190.70, GlobalFields={"service":"timer-job-3"}, Code=PARAMS INVALID, Error=params invalid, include(size need > 5, code need > 0)
func Errorf ¶ added in v0.1.2
Errorf new error with format
Example ¶
new error with format
package main import ( "fmt" "github.com/researchlab/gdk" ) func main() { const MIN_VALUE = 5 const ERR_PARAMS_INVALID = "ERR PARAMS INVALID" err := gdk.Errorf("params invalid, size need > %d", MIN_VALUE).WithCode(ERR_PARAMS_INVALID) fmt.Println(err.DetailText()) }
Output: CallChains=ExampleErrorf, Code=ERR PARAMS INVALID, Error=params invalid, size need > 5
type ErrDetail ¶ added in v0.1.2
type ErrDetail struct { Chains []string `json:"CallChains,omitempty"` // 反序列化时,如果该字段为空,则不进行序列化输出 GlobalTag string `json:"GlobalTag,omitempty"` Tag string `json:"Tag,omitempty"` GlobalFields map[string]interface{} `json:"GlobalFields,omitempty"` Fields map[string]interface{} `json:"Fields,omitempty"` Code any `json:"Code,omitempty"` E string `json:"Error,omitempty"` // contains filtered or unexported fields }
ErrDetail error detail struct
type FileUploadInfo ¶ added in v0.1.2
FileUploadInfo upload file info struct
type Float ¶
Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.
type Functions ¶ added in v0.1.2
Functions bundle of functions
type Heap ¶ added in v0.1.3
type Heap[E any] struct { // contains filtered or unexported fields }
Heap base on generics to build a heap tree for any type
func NewHeap ¶ added in v0.1.3
NewHeap return Heap pointer and init the heap tree
Example ¶
package main import ( "fmt" "github.com/researchlab/gdk" ) type student struct { name string age int } func main() { h := gdk.NewHeap([]student{}, func(s1, s2 student) int { return s1.age - s2.age // age 小的先出 }) for i := 100; i > 0; i-- { h.Push(student{fmt.Sprintf("name%d", i), i}) } // 每次获取最小年龄的student student := h.Pop() fmt.Println(student.age) student = h.Pop() fmt.Println(student.age) }
Output: 1 2
func (*Heap[E]) Pop ¶ added in v0.1.3
func (h *Heap[E]) Pop() (e E)
Pop remove and return the minimum element(according to Less) from the heap. The complexity is O(log n) where n = h.Len() Pop is equivalent to Remove(h, 0).
type HttpOptions ¶ added in v0.1.2
type Info ¶ added in v0.1.3
type Info struct { Version string `json:"version"` GitBranch string `json:"gitBranch"` GitTag string `json:"gitTag"` GitCommit string `json:"gitCommit"` GitTreeState string `json:"gitTreeState"` BuildDate string `json:"buildDate"` GoVersion string `json:"goVersion"` Compiler string `json:"compiler"` Platform string `json:"platform"` }
Info contains versioning information.
func Version ¶ added in v0.1.3
func Version() Info
Example ¶
build binary by makefile, command make default -f version.Makefile ExampleVersion version examples
package main import ( "fmt" "net/http" "os" "github.com/researchlab/gdk" ) func main() { v := gdk.Version() // version by console cmd args := os.Args if len(args) >= 2 && args[1] == "version" { fmt.Println(v.String()) return } // version by http request http.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, v) }) http.ListenAndServe(":8082", nil) }
Output:
type Integer ¶
Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.
type Ordered ¶
Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.
type Signed ¶
Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.
type Stack ¶ added in v0.1.3
type Stack[E any] struct { // contains filtered or unexported fields }
Stack
func NewStackSize ¶ added in v0.1.3
func (*Stack[E]) Pop ¶ added in v0.1.3
func (s *Stack[E]) Pop() (e E)
Pop pop the element from the stack