gdk

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2023 License: MIT Imports: 25 Imported by: 0

README

Golang Development Kit (GDK™)

Go Report Card Coverage Status Quality Gate Status Reliability Rating Security Rating Maintainability Rating Bugs GoDoc GitHub release

The Golang Development Kit (GDK™) includes tools useful for developing and testing programs written in the Golang programming language.

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

Examples

Constants

View Source
const (
	G_TAG             = "globalTag"
	G_FIELDS          = "globalFields"
	G_ERROR_TEMPLATES = "globalErrorTemplates"
)
View Source
const (
	FORM_MULTIPART   = "multipart/form-data"
	FORM_ENCODED     = "application/x-www-form-urlencoded"
	APPLICATION_JSON = "application/json"
	CONTENT_TYPE     = "Content-Type"
)
View Source
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

View Source
var ERR_BYTES_INVALILD = errors.New("BytesToFloat64 bytes invalid")

ERR_BYTES_INVALILD

View Source
var ERR_NEED_NUMERIC = errors.New("ToInt64 need numeric")

ERR_NEED_NUMERIC

View Source
var (
	// ErrParamsNotAdapted  params length invalid
	ErrParamsNotAdapted = errors.New("The number of params is not adapted.")
)

Functions

func ArrayContains added in v0.1.2

func ArrayContains[E string | int64 | int | float64](array []E, key E) bool

ArrayContains return true if this array contains the specified element.

func ArrayMax added in v0.1.2

func ArrayMax[E Ordered](array ...E) E

ArrayMax return the max one

func ArrayMerge

func ArrayMerge[E string | int64 | int](arraya, arrayb []E, arrays ...[]E) (array []E)

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 ArraySum

func ArraySum[E int64 | int | float64](array []E) (sum E)

ArraySum sum of the given array

func ArrayToMap added in v0.1.3

func ArrayToMap[E, R, T any](array []E, f TFunc[E, R, T]) (out map[any]T)

ArrayToMap mapping the given array to a map[r]t

func ArrayUnique

func ArrayUnique[E int64 | int | string](in []E) (out []E)

ArrayUnique remove Duplicate item of the given array

func BytesToFloat64

func BytesToFloat64(bytes []byte) (data float64, err error)

BytesToFloat64 convert bytes to float64

func BytesToReadable

func BytesToReadable(bytes float64, precision ...int) string

BytesToReadable convert bytes to human readable string KB,MB,GB,TB,PB,EB,ZB,YB

func Create

func Create(name string) (*os.File, error)

Create create one file

func Dir

func Dir(fp string) string

Dir get filepath dir name

func DirsUnder

func DirsUnder(dirPath string) ([]string, error)

DirsUnder list dirs under dirPath

func EnsureDirRW

func EnsureDirRW(dataDir string) error

EnsureDirRW ensure the datadir and make sure it's rw-able

func Ext

func Ext(fp string) string

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 FileMTime

func FileMTime(fp string) (int64, error)

FileMTime get file modified time

func FileSize

func FileSize(fp string) (int64, error)

FileSize get file size as how many bytes

func FilesUnder

func FilesUnder(dirPath string) ([]string, error)

FilesUnder list files under dirPath

func Float64Precision

func Float64Precision(f float64, precision int, round bool) float64

Float64Precision float指定精度; round为true时, 表示支持四舍五入

func Float64ToBytes

func Float64ToBytes(input float64) []byte

Float64ToBytes convert float64 to bytes; []uint8

func Float64ToStr

func Float64ToStr(num float64, precision int) string

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 InsureDir

func InsureDir(fp string) error

InsureDir mkdir if not exist

func IsEmail added in v0.1.2

func IsEmail(email string) bool

IsEmail validates string is an email address, if not return false basically validation can match 99% cases

func IsEmailRFC added in v0.1.2

func IsEmailRFC(email string) bool

IsEmailRFC validates string is an email address, if not return false this validation omits RFC 2822

func IsExist

func IsExist(fp string) bool

IsExist checks whether a file or directory exists It returns false when the file or directory does not exist.

func IsFile

func IsFile(fp string) bool

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

func IsUrl(url string) bool

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

func MapToStruct(obj map[string]interface{}, data interface{}) (interface{}, error)

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 Name

func Name(fp string) string

Name get filepath base name

func RandomInts

func RandomInts(start int, end int, count int) []int

RandomInts 生成count个[start,end)结束的不重复的随机数

func ReadResponse added in v0.1.2

func ReadResponse(resp *http.Response) (bodyBytes []byte, isGzip bool, err error)

ReadResponse return http.Response.body, isGzip=true if contentEncoding=gzip

func RealPath

func RealPath(fp string) (string, error)

RealPath get absolute filepath, based on built executable file

func Remove

func Remove(name string) error

Remove remove one file

func Rename

func Rename(src string, target string) error

Rename rename file name

func SearchFile

func SearchFile(filename string, paths ...string) (fullPath string, err error)

Search a file in the give paths. this is often used in search config file in /etc ~/

func SearchFileWithAffix

func SearchFileWithAffix(dirPath, prefix, suffix string) (fullPath string, exist bool)

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 SelfDir

func SelfDir() string

SelfDir get compiled executable file directory

func SelfPath

func SelfPath() string

SelfPath gets compiled executable file absolute path

func SetGlobalErrorTemplates added in v0.1.2

func SetGlobalErrorTemplates(templates map[any]string)

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 SetGlobalTag added in v0.1.2

func SetGlobalTag(tag string)

SetGlobalTag global tag

func StrToFloat64

func StrToFloat64(str string, precision int) float64

StrToFloat64 convert string to float64, supported the given precision

func StrToFloat64Round

func StrToFloat64Round(str string, precision int, round bool) float64

StrToFloat64Round convert string to float64, supported the given precision and round

func StringReverse added in v0.1.2

func StringReverse(s string) (string, error)

Reverse to reverse the string

func StructToMap

func StructToMap(obj interface{}) map[string]interface{}

StructToMap struct convert to map

func ToInt64

func ToInt64(value interface{}) (d int64, err error)

ToInt64 convert any numeric value to int64

func UnsetGlobals added in v0.1.3

func UnsetGlobals(options ...string)

Types

type BiFunc

type BiFunc[R, T, U any] func(T, U) R

two-arity specialization of function

type CMP

type CMP[E any] BiFunc[int, E, E]

compare function

type Comparable

type Comparable[E any] interface {
	CompareTo(v E) int
}

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 EQL

type EQL[E any] BiFunc[bool, E, E]

equal function

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

func ErrorCause(e error) Err

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

func ErrorT(code any, a ...any) Err

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

func Errorf(format string, a ...any) Err

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

type FileUploadInfo struct {
	Name     string // form name
	Filepath string
	FileName string
}

FileUploadInfo upload file info struct

type Float

type Float interface {
	~float32 | ~float64
}

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 Func

type Func[R, T any] func(T) R

function provides one input argument and one return

type Functions added in v0.1.2

type Functions map[string]reflect.Value

Functions bundle of functions

func NewFunctions added in v0.1.2

func NewFunctions() Functions

NewFunctions function maps

func (Functions) Bind added in v0.1.2

func (f Functions) Bind(name string, fn interface{}) (err error)

Bind the function with the given function name

func (Functions) Call added in v0.1.2

func (f Functions) Call(name string, params ...interface{}) (result []reflect.Value, err error)

Call the function with the given name and params

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

func NewHeap[E any](t []E, cmp CMP[E]) *Heap[E]

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]) Copy added in v0.1.3

func (h *Heap[E]) Copy() *Heap[E]

Copy to copy heap

func (*Heap[E]) Element added in v0.1.3

func (h *Heap[E]) Element(index int) (e E, err error)

func (*Heap[E]) Len added in v0.1.3

func (h *Heap[E]) Len() int

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

func (*Heap[E]) Push added in v0.1.3

func (h *Heap[E]) Push(v E)

Push push the element x into the heap. The complexity is O(log n) where n = h.Len()

func (*Heap[E]) Remove added in v0.1.3

func (h *Heap[E]) Remove(index int) (e E)

Remove remove and return the element at index i from the heap. The complexity is O(log n) where n = h.Len()

type HttpOptions added in v0.1.2

type HttpOptions struct {
	C       *http.Client
	Url     string
	Params  map[string]string
	Headers map[string]string
	Files   []FileUploadInfo // special for HttpPostFile
	// contains filtered or unexported fields
}

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:

func (Info) String added in v0.1.3

func (info Info) String() string

String returns info as a human-friendly version string.

type Integer

type Integer interface {
	Signed | Unsigned
}

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

type Ordered interface {
	Integer | Float | ~string
}

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

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

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 NewStack added in v0.1.3

func NewStack[E any]() *Stack[E]

func NewStackSize added in v0.1.3

func NewStackSize[E any](size int) *Stack[E]

func (*Stack[E]) Cap added in v0.1.3

func (s *Stack[E]) Cap() int

Cap return capacity

func (*Stack[E]) Copy added in v0.1.3

func (s *Stack[E]) Copy() *Stack[E]

Copy copy to a new stack

func (*Stack[E]) IsEmpty added in v0.1.3

func (s *Stack[E]) IsEmpty() bool

IsEmpty return true if stack has elements

func (*Stack[E]) Pop added in v0.1.3

func (s *Stack[E]) Pop() (e E)

Pop pop the element from the stack

func (*Stack[E]) Push added in v0.1.3

func (s *Stack[E]) Push(e E)

Push push the element into the stack

func (*Stack[E]) Size added in v0.1.3

func (s *Stack[E]) Size() int

Size return the stack elements size

type TFunc added in v0.1.3

type TFunc[E, R, T any] func(E) (R, T)

TFunc provides one input and two return

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.

Jump to

Keyboard shortcuts

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