1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

fix: fix lint issue

This commit is contained in:
dudaodong
2022-12-10 16:41:40 +08:00
parent 2725575d2f
commit 13bbe19ab2
17 changed files with 142 additions and 98 deletions

View File

@@ -158,7 +158,7 @@ func (c *Channel) Bridge(ctx context.Context, chanStream <-chan <-chan any) <-ch
var stream <-chan any var stream <-chan any
select { select {
case maybeStream, ok := <-chanStream: case maybeStream, ok := <-chanStream:
if ok == false { if !ok {
return return
} }
stream = maybeStream stream = maybeStream

View File

@@ -97,38 +97,41 @@ func ToString(value any) string {
return "" return ""
} }
switch value.(type) { switch val := value.(type) {
case float32: case float32:
return strconv.FormatFloat(float64(value.(float32)), 'f', -1, 32) return strconv.FormatFloat(float64(val), 'f', -1, 32)
case float64: case float64:
return strconv.FormatFloat(value.(float64), 'f', -1, 64) return strconv.FormatFloat(val, 'f', -1, 64)
case int: case int:
return strconv.FormatInt(int64(value.(int)), 10) return strconv.FormatInt(int64(val), 10)
case int8: case int8:
return strconv.FormatInt(int64(value.(int8)), 10) return strconv.FormatInt(int64(val), 10)
case int16: case int16:
return strconv.FormatInt(int64(value.(int16)), 10) return strconv.FormatInt(int64(val), 10)
case int32: case int32:
return strconv.FormatInt(int64(value.(int32)), 10) return strconv.FormatInt(int64(val), 10)
case int64: case int64:
return strconv.FormatInt(value.(int64), 10) return strconv.FormatInt(val, 10)
case uint: case uint:
return strconv.FormatUint(uint64(value.(uint)), 10) return strconv.FormatUint(uint64(val), 10)
case uint8: case uint8:
return strconv.FormatUint(uint64(value.(uint8)), 10) return strconv.FormatUint(uint64(val), 10)
case uint16: case uint16:
return strconv.FormatUint(uint64(value.(uint16)), 10) return strconv.FormatUint(uint64(val), 10)
case uint32: case uint32:
return strconv.FormatUint(uint64(value.(uint32)), 10) return strconv.FormatUint(uint64(val), 10)
case uint64: case uint64:
return strconv.FormatUint(value.(uint64), 10) return strconv.FormatUint(val, 10)
case string: case string:
return value.(string) return val
case []byte: case []byte:
return string(value.([]byte)) return string(val)
default: default:
newValue, _ := json.Marshal(value) b, err := json.Marshal(val)
return string(newValue) if err != nil {
return ""
}
return string(b)
// todo: maybe we should't supprt other type conversion // todo: maybe we should't supprt other type conversion
// v := reflect.ValueOf(value) // v := reflect.ValueOf(value)

View File

@@ -27,14 +27,9 @@ func TestToChannel(t *testing.T) {
assert := internal.NewAssert(t, "TestToChannel") assert := internal.NewAssert(t, "TestToChannel")
ch := ToChannel([]int{1, 2, 3}) ch := ToChannel([]int{1, 2, 3})
val1, _ := <-ch assert.Equal(1, <-ch)
assert.Equal(1, val1) assert.Equal(2, <-ch)
assert.Equal(3, <-ch)
val2, _ := <-ch
assert.Equal(2, val2)
val3, _ := <-ch
assert.Equal(3, val3)
_, ok := <-ch _, ok := <-ch
assert.Equal(false, ok) assert.Equal(false, ok)
@@ -254,6 +249,7 @@ func TestDecodeByte(t *testing.T) {
var obj string var obj string
byteData := []byte{6, 12, 0, 3, 97, 98, 99} byteData := []byte{6, 12, 0, 3, 97, 98, 99}
DecodeByte(byteData, &obj) err := DecodeByte(byteData, &obj)
assert.IsNil(err)
assert.Equal("abc", obj) assert.Equal("abc", obj)
} }

View File

@@ -33,7 +33,11 @@ func GenerateRsaKey(keySize int, priKeyFile, pubKeyFile string) error {
if err != nil { if err != nil {
panic(err) panic(err)
} }
pem.Encode(file, &block) err = pem.Encode(file, &block)
if err != nil {
return err
}
file.Close() file.Close()
// public key // public key
@@ -49,12 +53,16 @@ func GenerateRsaKey(keySize int, priKeyFile, pubKeyFile string) error {
Bytes: derpText, Bytes: derpText,
} }
//file,err = os.Create("rsa_public.pem")
file, err = os.Create(pubKeyFile) file, err = os.Create(pubKeyFile)
if err != nil { if err != nil {
return err return err
} }
pem.Encode(file, &block)
err = pem.Encode(file, &block)
if err != nil {
return err
}
file.Close() file.Close()
return nil return nil
@@ -72,7 +80,11 @@ func RsaEncrypt(data []byte, pubKeyFileName string) []byte {
} }
defer file.Close() defer file.Close()
buf := make([]byte, fileInfo.Size()) buf := make([]byte, fileInfo.Size())
file.Read(buf)
_, err = file.Read(buf)
if err != nil {
panic(err)
}
block, _ := pem.Decode(buf) block, _ := pem.Decode(buf)
@@ -101,7 +113,12 @@ func RsaDecrypt(data []byte, privateKeyFileName string) []byte {
} }
buf := make([]byte, fileInfo.Size()) buf := make([]byte, fileInfo.Size())
defer file.Close() defer file.Close()
file.Read(buf) file.Read(buf)
_, err = file.Read(buf)
if err != nil {
panic(err)
}
block, _ := pem.Decode(buf) block, _ := pem.Decode(buf)

View File

@@ -146,9 +146,9 @@ func (h *MaxHeap[T]) PrintStructure() {
lastNum := powerTwo(level - 1) lastNum := powerTwo(level - 1)
lastLen := lastNum + (lastNum - 1) lastLen := lastNum + (lastNum - 1)
heapTree := make([][]string, level, level) heapTree := make([][]string, level)
for i := 0; i < level; i++ { for i := 0; i < level; i++ {
heapTree[i] = make([]string, lastLen, lastLen) heapTree[i] = make([]string, lastLen)
for j := 0; j < lastLen; j++ { for j := 0; j < lastLen; j++ {
heapTree[i][j] = "" heapTree[i][j] = ""
} }
@@ -169,9 +169,9 @@ func (h *MaxHeap[T]) PrintStructure() {
for n := 0; n < lastLen; n++ { for n := 0; n < lastLen; n++ {
val := heapTree[m][n] val := heapTree[m][n]
if val == "" { if val == "" {
fmt.Printf(" ") fmt.Print(" ")
} else { } else {
fmt.Printf(val) fmt.Print(val)
} }
} }
fmt.Println() fmt.Println()

View File

@@ -156,7 +156,7 @@ func (l *List[T]) DeleteAt(index int) {
return return
} }
if index == size-1 { if index == size-1 {
data = append(data[:index]) data = data[:index]
} else { } else {
data = append(data[:index], data[index+1:]...) data = append(data[:index], data[index+1:]...)
} }
@@ -174,7 +174,7 @@ func (l *List[T]) DeleteIf(f func(T) bool) int {
continue continue
} }
if index == size-1 { if index == size-1 {
data = append(data[:index]) data = data[:index]
} else { } else {
data = append(data[:index], data[index+1:]...) data = append(data[:index], data[index+1:]...)
index-- index--
@@ -221,7 +221,7 @@ func (l *List[T]) IsEmpty() bool {
// Clear the data of list // Clear the data of list
func (l *List[T]) Clear() { func (l *List[T]) Clear() {
l.data = make([]T, 0, 0) l.data = make([]T, 0)
} }
// Clone return a copy of list // 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 // Merge two list, return new list, don't change original list
func (l *List[T]) Merge(other *List[T]) *List[T] { func (l *List[T]) Merge(other *List[T]) *List[T] {
l1, l2 := len(l.data), len(other.data) 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...)...) data := append([]T{}, append(l.data, other.data...)...)
ml.data = data ml.data = data
@@ -274,7 +274,7 @@ func (l *List[T]) Unique() {
data := l.data data := l.data
size := len(data) size := len(data)
uniqueData := make([]T, 0, 0) uniqueData := make([]T, 0)
for i := 0; i < size; i++ { for i := 0; i < size; i++ {
value := data[i] value := data[i]
skip := true 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 // 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] { 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 { for _, v := range l.data {
if other.Contain(v) { if other.Contain(v) {

View File

@@ -38,35 +38,35 @@ func inOrderTraverse[T any](node *datastructure.TreeNode[T]) []T {
return data return data
} }
func preOrderPrint[T any](node *datastructure.TreeNode[T]) { // func preOrderPrint[T any](node *datastructure.TreeNode[T]) {
if node == nil { // if node == nil {
return // return
} // }
fmt.Printf("%v, ", node.Value) // fmt.Printf("%v, ", node.Value)
preOrderPrint(node.Left) // preOrderPrint(node.Left)
preOrderPrint(node.Right) // preOrderPrint(node.Right)
} // }
func postOrderPrint[T any](node *datastructure.TreeNode[T]) { // func postOrderPrint[T any](node *datastructure.TreeNode[T]) {
if node == nil { // if node == nil {
return // return
} // }
preOrderPrint(node.Left) // postOrderPrint(node.Left)
preOrderPrint(node.Right) // postOrderPrint(node.Right)
fmt.Printf("%v, ", node.Value) // fmt.Printf("%v, ", node.Value)
} // }
func inOrderPrint[T any](node *datastructure.TreeNode[T]) { // func inOrderPrint[T any](node *datastructure.TreeNode[T]) {
if node == nil { // if node == nil {
return // return
} // }
inOrderPrint(node.Left) // inOrderPrint(node.Left)
fmt.Printf("%v, ", node.Value) // fmt.Printf("%v, ", node.Value)
inOrderPrint(node.Right) // inOrderPrint(node.Right)
} // }
func levelOrderTraverse[T any](root *datastructure.TreeNode[T], traversal *[]T) { func levelOrderTraverse[T any](root *datastructure.TreeNode[T], traversal *[]T) {
var q []*datastructure.TreeNode[T] // queue var q []*datastructure.TreeNode[T] // queue

View File

@@ -11,7 +11,6 @@ import (
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
"io/ioutil"
"net/http" "net/http"
"os" "os"
"path" "path"
@@ -78,13 +77,16 @@ func CopyFile(srcFilePath string, dstFilePath string) error {
var tmp = make([]byte, 1024*4) var tmp = make([]byte, 1024*4)
for { for {
n, err := srcFile.Read(tmp) n, err := srcFile.Read(tmp)
distFile.Write(tmp[:n])
if err != nil { if err != nil {
if err == io.EOF { if err == io.EOF {
return nil return nil
} }
return err 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 //ReadFileToString return string of file content
func ReadFileToString(path string) (string, error) { func ReadFileToString(path string) (string, error) {
bytes, err := ioutil.ReadFile(path) bytes, err := os.ReadFile(path)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -141,7 +143,7 @@ func ListFileNames(path string) ([]string, error) {
return []string{}, nil return []string{}, nil
} }
fs, err := ioutil.ReadDir(path) fs, err := os.ReadDir(path)
if err != nil { if err != nil {
return []string{}, err return []string{}, err
} }
@@ -172,7 +174,7 @@ func Zip(fpath string, destPath string) error {
archive := zip.NewWriter(zipFile) archive := zip.NewWriter(zipFile)
defer archive.Close() 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 { if err != nil {
return err return err
} }
@@ -209,6 +211,10 @@ func Zip(fpath string, destPath string) error {
return nil return nil
}) })
if err != nil {
return err
}
return nil return nil
} }
@@ -229,9 +235,13 @@ func UnZip(zipFile string, destPath string) error {
} }
if f.FileInfo().IsDir() { if f.FileInfo().IsDir() {
os.MkdirAll(path, os.ModePerm) err = os.MkdirAll(path, os.ModePerm)
if err != nil {
return err
}
} else { } 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 return err
} }

View File

@@ -25,9 +25,10 @@ func TestCreateFile(t *testing.T) {
f := "./text.txt" f := "./text.txt"
if CreateFile(f) { if CreateFile(f) {
file, err := os.Open(f) file, err := os.Open(f)
defer file.Close()
assert.IsNil(err) assert.IsNil(err)
assert.Equal(f, file.Name()) assert.Equal(f, file.Name())
defer file.Close()
} else { } else {
t.FailNow() t.FailNow()
} }
@@ -113,7 +114,11 @@ func TestReadFileToString(t *testing.T) {
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777) f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
defer f.Close() defer f.Close()
f.WriteString("hello world")
_, err := f.WriteString("hello world")
if err != nil {
t.Log(err)
}
content, _ := ReadFileToString(path) content, _ := ReadFileToString(path)
assert.Equal("hello world", content) 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) f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
defer f.Close() 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) assert.IsNil(err)
content, _ := ReadFileToString(path) content, _ := ReadFileToString(path)
@@ -148,8 +156,13 @@ func TestReadFileByLine(t *testing.T) {
CreateFile(path) CreateFile(path)
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777) f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
defer f.Close() defer f.Close()
f.WriteString("hello\nworld")
_, err := f.WriteString("hello\nworld")
if err != nil {
t.Log(err)
}
expected := []string{"hello", "world"} expected := []string{"hello", "world"}
actual, _ := ReadFileByLine(path) actual, _ := ReadFileByLine(path)

View File

@@ -84,10 +84,8 @@ func Debounced(fn func(), duration time.Duration) func() {
go func() { go func() {
for { for {
select { <-timer.C
case <-timer.C: go fn()
go fn()
}
} }
}() }()

View File

@@ -157,10 +157,7 @@ type rangeIterator[T lancetconstraints.Number] struct {
} }
func (iter *rangeIterator[T]) HasNext() bool { func (iter *rangeIterator[T]) HasNext() bool {
if iter.start >= iter.end { return iter.start < iter.end
return false
}
return true
} }
func (iter *rangeIterator[T]) Next() (T, bool) { func (iter *rangeIterator[T]) Next() (T, bool) {

View File

@@ -85,7 +85,7 @@ func Intersect[K comparable, V any](maps ...map[K]V) map[K]V {
return m return m
} }
reduceMaps := make([]map[K]V, 2, 2) reduceMaps := make([]map[K]V, 2)
result = reducer(maps[0], maps[1]) result = reducer(maps[0], maps[1])
for i := 2; i < len(maps); i++ { for i := 2; i < len(maps); i++ {

View File

@@ -108,7 +108,11 @@ func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, err
client.setTLS(rawUrl) client.setTLS(rawUrl)
client.setHeader(req, request.Headers) 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 { if request.FormData != nil {
client.setFormData(req, request.FormData) client.setFormData(req, request.FormData)

View File

@@ -32,7 +32,10 @@ func TestHttpClient_Get(t *testing.T) {
} }
var todo Todo var todo Todo
httpClient.DecodeResponse(resp, &todo) err = httpClient.DecodeResponse(resp, &todo)
if err != nil {
t.Log(err)
}
assert.Equal(1, todo.Id) assert.Equal(1, todo.Id)
} }

View File

@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"io/ioutil" "io/ioutil"
"log" "log"
"net/url"
"testing" "testing"
"github.com/duke-git/lancet/v2/internal" "github.com/duke-git/lancet/v2/internal"
@@ -54,13 +55,13 @@ func TestHttpPostFormData(t *testing.T) {
UserId int `json:"userId"` UserId int `json:"userId"`
Title string `json:"title"` Title string `json:"title"`
} }
// postData := url.Values{} postData := url.Values{}
// postData.Add("userId", "1") postData.Add("userId", "1")
// postData.Add("title", "TestAddToDo") postData.Add("title", "TestToDo")
postData := make(map[string]string) // postData := make(map[string]string)
postData["userId"] = "1" // postData["userId"] = "1"
postData["title"] = "title" // postData["title"] = "title"
resp, err := HttpPost(apiUrl, header, postData, nil) resp, err := HttpPost(apiUrl, header, postData, nil)
if err != nil { if err != nil {

View File

@@ -2,7 +2,7 @@ package netutil
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@@ -55,7 +55,7 @@ func GetPublicIpInfo() (*PublicIpInfo, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -25,7 +25,9 @@ func TestOsEnvOperation(t *testing.T) {
envNotExist := GetOsEnv("foo") envNotExist := GetOsEnv("foo")
assert.Equal("", envNotExist) assert.Equal("", envNotExist)
SetOsEnv("foo", "foo_value") err := SetOsEnv("foo", "foo_value")
assert.IsNil(err)
envExist := GetOsEnv("foo") envExist := GetOsEnv("foo")
assert.Equal("foo_value", envExist) 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"))
assert.Equal(false, CompareOsEnv("abc", "abc")) assert.Equal(false, CompareOsEnv("abc", "abc"))
err := RemoveOsEnv("foo") err = RemoveOsEnv("foo")
if err != nil { if err != nil {
t.Fail() t.Fail()
} }