diff --git a/concurrency/channel.go b/concurrency/channel.go index fad8333..9f40dd3 100644 --- a/concurrency/channel.go +++ b/concurrency/channel.go @@ -158,7 +158,7 @@ func (c *Channel) Bridge(ctx context.Context, chanStream <-chan <-chan any) <-ch var stream <-chan any select { case maybeStream, ok := <-chanStream: - if ok == false { + if !ok { return } stream = maybeStream diff --git a/convertor/convertor.go b/convertor/convertor.go index 265246b..9d9996d 100644 --- a/convertor/convertor.go +++ b/convertor/convertor.go @@ -97,38 +97,41 @@ func ToString(value any) string { return "" } - switch value.(type) { + switch val := value.(type) { case float32: - return strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32) + return strconv.FormatFloat(float64(val), 'f', -1, 32) case float64: - return strconv.FormatFloat(value.(float64), 'f', -1, 64) + return strconv.FormatFloat(val, 'f', -1, 64) case int: - return strconv.FormatInt(int64(value.(int)), 10) + return strconv.FormatInt(int64(val), 10) case int8: - return strconv.FormatInt(int64(value.(int8)), 10) + return strconv.FormatInt(int64(val), 10) case int16: - return strconv.FormatInt(int64(value.(int16)), 10) + return strconv.FormatInt(int64(val), 10) case int32: - return strconv.FormatInt(int64(value.(int32)), 10) + return strconv.FormatInt(int64(val), 10) case int64: - return strconv.FormatInt(value.(int64), 10) + return strconv.FormatInt(val, 10) case uint: - return strconv.FormatUint(uint64(value.(uint)), 10) + return strconv.FormatUint(uint64(val), 10) case uint8: - return strconv.FormatUint(uint64(value.(uint8)), 10) + return strconv.FormatUint(uint64(val), 10) case uint16: - return strconv.FormatUint(uint64(value.(uint16)), 10) + return strconv.FormatUint(uint64(val), 10) case uint32: - return strconv.FormatUint(uint64(value.(uint32)), 10) + return strconv.FormatUint(uint64(val), 10) case uint64: - return strconv.FormatUint(value.(uint64), 10) + return strconv.FormatUint(val, 10) case string: - return value.(string) + return val case []byte: - return string(value.([]byte)) + return string(val) default: - newValue, _ := json.Marshal(value) - return string(newValue) + b, err := json.Marshal(val) + if err != nil { + return "" + } + return string(b) // todo: maybe we should't supprt other type conversion // v := reflect.ValueOf(value) diff --git a/convertor/convertor_test.go b/convertor/convertor_test.go index 512cab7..fbfd81c 100644 --- a/convertor/convertor_test.go +++ b/convertor/convertor_test.go @@ -27,14 +27,9 @@ func TestToChannel(t *testing.T) { assert := internal.NewAssert(t, "TestToChannel") ch := ToChannel([]int{1, 2, 3}) - val1, _ := <-ch - assert.Equal(1, val1) - - val2, _ := <-ch - assert.Equal(2, val2) - - val3, _ := <-ch - assert.Equal(3, val3) + assert.Equal(1, <-ch) + assert.Equal(2, <-ch) + assert.Equal(3, <-ch) _, ok := <-ch assert.Equal(false, ok) @@ -254,6 +249,7 @@ func TestDecodeByte(t *testing.T) { var obj string byteData := []byte{6, 12, 0, 3, 97, 98, 99} - DecodeByte(byteData, &obj) + err := DecodeByte(byteData, &obj) + assert.IsNil(err) assert.Equal("abc", obj) } diff --git a/cryptor/rsa.go b/cryptor/rsa.go index 4b8440a..27a43e4 100644 --- a/cryptor/rsa.go +++ b/cryptor/rsa.go @@ -33,7 +33,11 @@ func GenerateRsaKey(keySize int, priKeyFile, pubKeyFile string) error { if err != nil { panic(err) } - pem.Encode(file, &block) + err = pem.Encode(file, &block) + if err != nil { + return err + } + file.Close() // public key @@ -49,12 +53,16 @@ func GenerateRsaKey(keySize int, priKeyFile, pubKeyFile string) error { Bytes: derpText, } - //file,err = os.Create("rsa_public.pem") file, err = os.Create(pubKeyFile) if err != nil { return err } - pem.Encode(file, &block) + + err = pem.Encode(file, &block) + if err != nil { + return err + } + file.Close() return nil @@ -72,7 +80,11 @@ func RsaEncrypt(data []byte, pubKeyFileName string) []byte { } defer file.Close() buf := make([]byte, fileInfo.Size()) - file.Read(buf) + + _, err = file.Read(buf) + if err != nil { + panic(err) + } block, _ := pem.Decode(buf) @@ -101,7 +113,12 @@ func RsaDecrypt(data []byte, privateKeyFileName string) []byte { } buf := make([]byte, fileInfo.Size()) defer file.Close() + file.Read(buf) + _, err = file.Read(buf) + if err != nil { + panic(err) + } block, _ := pem.Decode(buf) diff --git a/datastructure/heap/maxheap.go b/datastructure/heap/maxheap.go index 595d044..1fa56cc 100644 --- a/datastructure/heap/maxheap.go +++ b/datastructure/heap/maxheap.go @@ -146,9 +146,9 @@ func (h *MaxHeap[T]) PrintStructure() { lastNum := powerTwo(level - 1) lastLen := lastNum + (lastNum - 1) - heapTree := make([][]string, level, level) + heapTree := make([][]string, level) for i := 0; i < level; i++ { - heapTree[i] = make([]string, lastLen, lastLen) + heapTree[i] = make([]string, lastLen) for j := 0; j < lastLen; j++ { heapTree[i][j] = "" } @@ -169,9 +169,9 @@ func (h *MaxHeap[T]) PrintStructure() { for n := 0; n < lastLen; n++ { val := heapTree[m][n] if val == "" { - fmt.Printf(" ") + fmt.Print(" ") } else { - fmt.Printf(val) + fmt.Print(val) } } fmt.Println() diff --git a/datastructure/list/list.go b/datastructure/list/list.go index 0f99123..199dd59 100644 --- a/datastructure/list/list.go +++ b/datastructure/list/list.go @@ -156,7 +156,7 @@ func (l *List[T]) DeleteAt(index int) { return } if index == size-1 { - data = append(data[:index]) + data = data[:index] } else { data = append(data[:index], data[index+1:]...) } @@ -174,7 +174,7 @@ func (l *List[T]) DeleteIf(f func(T) bool) int { continue } if index == size-1 { - data = append(data[:index]) + data = data[:index] } else { data = append(data[:index], data[index+1:]...) index-- @@ -221,7 +221,7 @@ func (l *List[T]) IsEmpty() bool { // Clear the data of list func (l *List[T]) Clear() { - l.data = make([]T, 0, 0) + l.data = make([]T, 0) } // Clone return a copy of list @@ -235,7 +235,7 @@ func (l *List[T]) Clone() *List[T] { // Merge two list, return new list, don't change original list func (l *List[T]) Merge(other *List[T]) *List[T] { l1, l2 := len(l.data), len(other.data) - ml := NewList(make([]T, l1+l2, l1+l2)) + ml := NewList(make([]T, l1+l2)) data := append([]T{}, append(l.data, other.data...)...) ml.data = data @@ -274,7 +274,7 @@ func (l *List[T]) Unique() { data := l.data size := len(data) - uniqueData := make([]T, 0, 0) + uniqueData := make([]T, 0) for i := 0; i < size; i++ { value := data[i] skip := true @@ -305,7 +305,7 @@ func (l *List[T]) Union(other *List[T]) *List[T] { // Intersection creates a new list whose element both be contained in list l and other func (l *List[T]) Intersection(other *List[T]) *List[T] { - result := NewList(make([]T, 0, 0)) + result := NewList(make([]T, 0)) for _, v := range l.data { if other.Contain(v) { diff --git a/datastructure/tree/tree_internal.go b/datastructure/tree/tree_internal.go index ccc28f3..940fe25 100644 --- a/datastructure/tree/tree_internal.go +++ b/datastructure/tree/tree_internal.go @@ -38,35 +38,35 @@ func inOrderTraverse[T any](node *datastructure.TreeNode[T]) []T { return data } -func preOrderPrint[T any](node *datastructure.TreeNode[T]) { - if node == nil { - return - } +// func preOrderPrint[T any](node *datastructure.TreeNode[T]) { +// if node == nil { +// return +// } - fmt.Printf("%v, ", node.Value) - preOrderPrint(node.Left) - preOrderPrint(node.Right) -} +// fmt.Printf("%v, ", node.Value) +// preOrderPrint(node.Left) +// preOrderPrint(node.Right) +// } -func postOrderPrint[T any](node *datastructure.TreeNode[T]) { - if node == nil { - return - } +// func postOrderPrint[T any](node *datastructure.TreeNode[T]) { +// if node == nil { +// return +// } - preOrderPrint(node.Left) - preOrderPrint(node.Right) - fmt.Printf("%v, ", node.Value) -} +// postOrderPrint(node.Left) +// postOrderPrint(node.Right) +// fmt.Printf("%v, ", node.Value) +// } -func inOrderPrint[T any](node *datastructure.TreeNode[T]) { - if node == nil { - return - } +// func inOrderPrint[T any](node *datastructure.TreeNode[T]) { +// if node == nil { +// return +// } - inOrderPrint(node.Left) - fmt.Printf("%v, ", node.Value) - inOrderPrint(node.Right) -} +// inOrderPrint(node.Left) +// fmt.Printf("%v, ", node.Value) +// inOrderPrint(node.Right) +// } func levelOrderTraverse[T any](root *datastructure.TreeNode[T], traversal *[]T) { var q []*datastructure.TreeNode[T] // queue diff --git a/fileutil/file.go b/fileutil/file.go index efa8c14..6423eef 100644 --- a/fileutil/file.go +++ b/fileutil/file.go @@ -11,7 +11,6 @@ import ( "fmt" "io" "io/fs" - "io/ioutil" "net/http" "os" "path" @@ -78,13 +77,16 @@ func CopyFile(srcFilePath string, dstFilePath string) error { var tmp = make([]byte, 1024*4) for { n, err := srcFile.Read(tmp) - distFile.Write(tmp[:n]) if err != nil { if err == io.EOF { return nil } return err } + _, err = distFile.Write(tmp[:n]) + if err != nil { + return err + } } } @@ -102,7 +104,7 @@ func ClearFile(path string) error { //ReadFileToString return string of file content func ReadFileToString(path string) (string, error) { - bytes, err := ioutil.ReadFile(path) + bytes, err := os.ReadFile(path) if err != nil { return "", err } @@ -141,7 +143,7 @@ func ListFileNames(path string) ([]string, error) { return []string{}, nil } - fs, err := ioutil.ReadDir(path) + fs, err := os.ReadDir(path) if err != nil { return []string{}, err } @@ -172,7 +174,7 @@ func Zip(fpath string, destPath string) error { archive := zip.NewWriter(zipFile) defer archive.Close() - filepath.Walk(fpath, func(path string, info os.FileInfo, err error) error { + err = filepath.Walk(fpath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } @@ -209,6 +211,10 @@ func Zip(fpath string, destPath string) error { return nil }) + if err != nil { + return err + } + return nil } @@ -229,9 +235,13 @@ func UnZip(zipFile string, destPath string) error { } if f.FileInfo().IsDir() { - os.MkdirAll(path, os.ModePerm) + err = os.MkdirAll(path, os.ModePerm) + if err != nil { + return err + } } else { - if err = os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil { + err = os.MkdirAll(filepath.Dir(path), os.ModePerm) + if err != nil { return err } diff --git a/fileutil/file_test.go b/fileutil/file_test.go index 607fce4..6530a5a 100644 --- a/fileutil/file_test.go +++ b/fileutil/file_test.go @@ -25,9 +25,10 @@ func TestCreateFile(t *testing.T) { f := "./text.txt" if CreateFile(f) { file, err := os.Open(f) - defer file.Close() assert.IsNil(err) assert.Equal(f, file.Name()) + + defer file.Close() } else { t.FailNow() } @@ -113,7 +114,11 @@ func TestReadFileToString(t *testing.T) { f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777) defer f.Close() - f.WriteString("hello world") + + _, err := f.WriteString("hello world") + if err != nil { + t.Log(err) + } content, _ := ReadFileToString(path) assert.Equal("hello world", content) @@ -130,9 +135,12 @@ func TestClearFile(t *testing.T) { f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777) defer f.Close() - f.WriteString("hello world") + _, err := f.WriteString("hello world") + if err != nil { + t.Log(err) + } - err := ClearFile(path) + err = ClearFile(path) assert.IsNil(err) content, _ := ReadFileToString(path) @@ -148,8 +156,13 @@ func TestReadFileByLine(t *testing.T) { CreateFile(path) f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777) + defer f.Close() - f.WriteString("hello\nworld") + + _, err := f.WriteString("hello\nworld") + if err != nil { + t.Log(err) + } expected := []string{"hello", "world"} actual, _ := ReadFileByLine(path) diff --git a/function/function.go b/function/function.go index c6356c8..6846696 100644 --- a/function/function.go +++ b/function/function.go @@ -84,10 +84,8 @@ func Debounced(fn func(), duration time.Duration) func() { go func() { for { - select { - case <-timer.C: - go fn() - } + <-timer.C + go fn() } }() diff --git a/iterator/iterator.go b/iterator/iterator.go index 4b899de..f55ade4 100644 --- a/iterator/iterator.go +++ b/iterator/iterator.go @@ -157,10 +157,7 @@ type rangeIterator[T lancetconstraints.Number] struct { } func (iter *rangeIterator[T]) HasNext() bool { - if iter.start >= iter.end { - return false - } - return true + return iter.start < iter.end } func (iter *rangeIterator[T]) Next() (T, bool) { diff --git a/maputil/map.go b/maputil/map.go index 55d08e1..bf63196 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -85,7 +85,7 @@ func Intersect[K comparable, V any](maps ...map[K]V) map[K]V { return m } - reduceMaps := make([]map[K]V, 2, 2) + reduceMaps := make([]map[K]V, 2) result = reducer(maps[0], maps[1]) for i := 2; i < len(maps); i++ { diff --git a/netutil/http_client.go b/netutil/http_client.go index 030d936..5bf71cf 100644 --- a/netutil/http_client.go +++ b/netutil/http_client.go @@ -108,7 +108,11 @@ func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, err client.setTLS(rawUrl) client.setHeader(req, request.Headers) - client.setQueryParam(req, rawUrl, request.QueryParams) + + err = client.setQueryParam(req, rawUrl, request.QueryParams) + if err != nil { + return nil, err + } if request.FormData != nil { client.setFormData(req, request.FormData) diff --git a/netutil/http_client_test.go b/netutil/http_client_test.go index ceb9ce1..97f436d 100644 --- a/netutil/http_client_test.go +++ b/netutil/http_client_test.go @@ -32,7 +32,10 @@ func TestHttpClient_Get(t *testing.T) { } var todo Todo - httpClient.DecodeResponse(resp, &todo) + err = httpClient.DecodeResponse(resp, &todo) + if err != nil { + t.Log(err) + } assert.Equal(1, todo.Id) } diff --git a/netutil/http_test.go b/netutil/http_test.go index a9f0d3f..b530bea 100644 --- a/netutil/http_test.go +++ b/netutil/http_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "io/ioutil" "log" + "net/url" "testing" "github.com/duke-git/lancet/v2/internal" @@ -54,13 +55,13 @@ func TestHttpPostFormData(t *testing.T) { UserId int `json:"userId"` Title string `json:"title"` } - // postData := url.Values{} - // postData.Add("userId", "1") - // postData.Add("title", "TestAddToDo") + postData := url.Values{} + postData.Add("userId", "1") + postData.Add("title", "TestToDo") - postData := make(map[string]string) - postData["userId"] = "1" - postData["title"] = "title" + // postData := make(map[string]string) + // postData["userId"] = "1" + // postData["title"] = "title" resp, err := HttpPost(apiUrl, header, postData, nil) if err != nil { diff --git a/netutil/net.go b/netutil/net.go index 6960de0..cb62aaf 100644 --- a/netutil/net.go +++ b/netutil/net.go @@ -2,7 +2,7 @@ package netutil import ( "encoding/json" - "io/ioutil" + "io" "net" "net/http" "net/url" @@ -55,7 +55,7 @@ func GetPublicIpInfo() (*PublicIpInfo, error) { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/system/os_test.go b/system/os_test.go index a21cbd9..d084c15 100644 --- a/system/os_test.go +++ b/system/os_test.go @@ -25,7 +25,9 @@ func TestOsEnvOperation(t *testing.T) { envNotExist := GetOsEnv("foo") assert.Equal("", envNotExist) - SetOsEnv("foo", "foo_value") + err := SetOsEnv("foo", "foo_value") + assert.IsNil(err) + envExist := GetOsEnv("foo") assert.Equal("foo_value", envExist) @@ -34,7 +36,7 @@ func TestOsEnvOperation(t *testing.T) { assert.Equal(false, CompareOsEnv("abc", "abc")) assert.Equal(false, CompareOsEnv("abc", "abc")) - err := RemoveOsEnv("foo") + err = RemoveOsEnv("foo") if err != nil { t.Fail() }