Skip to content

Commit 492219c

Browse files
author
willzhen
committed
Init commit
0 parents  commit 492219c

40 files changed

+2970
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
go.sum

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# GO library
2+
- client:调用第三方服务的客户端。
3+
- ti: ti 平台客户端。
4+
- ti3.4
5+
- ti3.7
6+
- httpcall:http 调用的封装。
7+
- json_post.go: JsonPost。
8+
- json_get.go: JsonGet。
9+
- json_put.go: JsonPut。
10+
- json_delete.go: JsonDelete。
11+
- misc:常用的公共函数库
12+
- time_related:时间相关的函数
13+
- time_tick.go: TimeTick -- 计时器。
14+
- timed.go: Timed -- 函数计时调用。
15+
- goroutine_help.go:
16+
- GoroutineHelp.Recoverd:协程 recover。
17+
- GoroutineHelp.SafeGo:安全的 go。
18+
- retry.go: Retry -- 带重试调用。
19+
- id.go:
20+
- GenerateRandomString:生成随机字符串。
21+
- GenerateUUID:生成UUID。
22+
- BighumpToUnderscore:大驼峰参数转换成下划线。
23+
- UnderscoreToBighump:下划线参数转换成大驼峰。
24+
- log.og
25+
- FoldLog: 折叠日志中数据过长的字段,仅支持 json。
26+
- stl_extension:stl 的扩展
27+
- limit_waitgroup.go:LimitWaitGroup -- 对于系统 WaitGroup 的扩展,支持 limit 并发限制并且阻塞。
28+
- ordered_map.go:OrderedMap -- 实现了 c++ 中的排序 map,可以按照顺序遍历所有元素。
29+
- text: 文本处理相关方法
30+
- aho_automaton.go:ac 自动机,多模式串快速匹配。在一个文本中找出来,出现过哪些字符串子串以及其定位。可以理解对同一文本 s 多次调用 strings.Contains(s, xxx) 的加速。
31+
- BuildAcTrie: 构建自动机。
32+
- AcTrie.Search: 匹配。
33+
- edit_distance.go:
34+
- Levenshtein:文本编辑距离。
35+
- TextSim:计算两个文本的相似度。

go.mod

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
module github.com/memory-overflow/go-common-library
2+
3+
go 1.16
4+
5+
require (
6+
github.com/eapache/queue v1.1.0
7+
github.com/google/uuid v1.3.0
8+
github.com/json-iterator/go v1.1.12
9+
github.com/tidwall/gjson v1.14.4
10+
)

httpcall/httpcall_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package httpcall_test
2+
3+
import (
4+
"context"
5+
"testing"
6+
"time"
7+
8+
"github.com/memory-overflow/go-common-library/httpcall"
9+
service "github.com/memory-overflow/go-common-library/task_scheduler/example/add_service"
10+
)
11+
12+
func TestJsonPost(t *testing.T) {
13+
// 控制请求超时时间
14+
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
15+
defer cancel()
16+
uri := "http://127.0.0.1:8000/add"
17+
req := &service.AddRequest{
18+
A: 1,
19+
B: 2,
20+
}
21+
rsp := &service.AddResponse{}
22+
err := httpcall.JsonPost(ctx, uri, nil, req, rsp)
23+
if err != nil {
24+
t.Fatalf("JsonPost err: %v", err)
25+
}
26+
t.Logf("add taskId: %d", rsp.TaskId)
27+
}

httpcall/json_delete.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package httpcall
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/json"
7+
"fmt"
8+
"io/ioutil"
9+
"net/http"
10+
)
11+
12+
// JsonDelete http delete 请求
13+
func JsonDelete(ctx context.Context, uri string, header map[string]string, req, rsp interface{}) (err error) {
14+
body, _ := json.Marshal(req)
15+
reqCtx, err := http.NewRequestWithContext(ctx, http.MethodDelete, uri, bytes.NewReader(body))
16+
if err != nil {
17+
return fmt.Errorf("JsonDelete make NewRequest error: %v", err)
18+
}
19+
20+
for head, value := range header {
21+
reqCtx.Header.Set(head, value)
22+
}
23+
24+
response, err := http.DefaultClient.Do(reqCtx)
25+
if err != nil {
26+
return fmt.Errorf("JsonDelete do request error: %v", err)
27+
}
28+
defer response.Body.Close()
29+
if response.StatusCode != http.StatusOK {
30+
return fmt.Errorf("JsonDelete response status error, statuscode: %d, reason: %s",
31+
response.StatusCode, response.Status)
32+
}
33+
data, _ := ioutil.ReadAll(response.Body)
34+
// log.Printf("JsonDelete req: %v, rsp: %v \n", string(body), string(data))
35+
if rsp != nil {
36+
err = json.Unmarshal(data, rsp)
37+
if err != nil {
38+
return fmt.Errorf("JsonDelete response protocol error: %v, data: %s", err, string(data))
39+
}
40+
}
41+
return nil
42+
}

httpcall/json_get.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package httpcall
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"io/ioutil"
8+
"net/http"
9+
)
10+
11+
// JsonGet http json get 请求
12+
func JsonGet(ctx context.Context, uri string, header map[string]string, rsp interface{}) (err error) {
13+
reqCtx, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
14+
if err != nil {
15+
return fmt.Errorf("JsonGet make NewRequest error: %v", err)
16+
}
17+
18+
for head, value := range header {
19+
reqCtx.Header.Set(head, value)
20+
}
21+
22+
response, err := http.DefaultClient.Do(reqCtx)
23+
if err != nil {
24+
return fmt.Errorf("JsonGet do request error: %v", err)
25+
}
26+
defer response.Body.Close()
27+
if response.StatusCode != http.StatusOK {
28+
return fmt.Errorf("JsonGet response status error, statuscode: %d, reason: %s",
29+
response.StatusCode, response.Status)
30+
}
31+
data, _ := ioutil.ReadAll(response.Body)
32+
if rsp != nil {
33+
err = json.Unmarshal(data, rsp)
34+
if err != nil {
35+
return fmt.Errorf("JsonGet response protocol error: %v, data: %s", err, string(data))
36+
}
37+
}
38+
return nil
39+
}

httpcall/json_post.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package httpcall
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/json"
7+
"fmt"
8+
"io/ioutil"
9+
"net/http"
10+
)
11+
12+
// JsonPost http json post 请求
13+
func JsonPost(ctx context.Context, uri string, header map[string]string, req, rsp interface{}) (err error) {
14+
body, _ := json.Marshal(req)
15+
reqCtx, err := http.NewRequestWithContext(ctx, http.MethodPost, uri, bytes.NewReader(body))
16+
if err != nil {
17+
return fmt.Errorf("HttpPost make NewRequest error: %v", err)
18+
}
19+
if header == nil {
20+
reqCtx.Header.Set("Content-Type", "application/json")
21+
} else {
22+
for head, value := range header {
23+
reqCtx.Header.Set(head, value)
24+
}
25+
}
26+
response, err := http.DefaultClient.Do(reqCtx)
27+
if err != nil {
28+
return fmt.Errorf("HttpPost do request error: %v", err)
29+
}
30+
defer response.Body.Close()
31+
if response.StatusCode != http.StatusOK {
32+
return fmt.Errorf("HttpPost response status error, statuscode: %d, reason: %s",
33+
response.StatusCode, response.Status)
34+
}
35+
data, _ := ioutil.ReadAll(response.Body)
36+
// log.Printf("JsonPost req: %v, rsp: %v \n", string(body), string(data))
37+
if rsp != nil {
38+
err = json.Unmarshal(data, rsp)
39+
if err != nil {
40+
return fmt.Errorf("HttpPost response protocol error: %v, data: %s", err, string(data))
41+
}
42+
}
43+
return nil
44+
}

httpcall/json_put.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package httpcall
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/json"
7+
"fmt"
8+
"io/ioutil"
9+
"net/http"
10+
)
11+
12+
// JsonPut http put 请求
13+
func JsonPut(ctx context.Context, uri string, header map[string]string, req, rsp interface{}) (err error) {
14+
body, ok := req.([]byte)
15+
if !ok {
16+
body, _ = json.Marshal(req)
17+
}
18+
reqCtx, err := http.NewRequestWithContext(ctx, http.MethodPut, uri, bytes.NewReader(body))
19+
if err != nil {
20+
return fmt.Errorf("JsonPut make NewRequest error: %v", err)
21+
}
22+
if header == nil {
23+
reqCtx.Header.Set("Content-Type", "application/octet-stream")
24+
} else {
25+
for head, value := range header {
26+
reqCtx.Header.Set(head, value)
27+
}
28+
}
29+
response, err := http.DefaultClient.Do(reqCtx)
30+
if err != nil {
31+
return fmt.Errorf("JsonPut do request error: %v", err)
32+
}
33+
defer response.Body.Close()
34+
if response.StatusCode != http.StatusOK {
35+
return fmt.Errorf("JsonPut response status error, statuscode: %d, reason: %s",
36+
response.StatusCode, response.Status)
37+
}
38+
data, _ := ioutil.ReadAll(response.Body)
39+
// log.Printf("JsonPut req: %v, rsp: %v \n", string(body), string(data))
40+
if rsp != nil {
41+
err = json.Unmarshal(data, rsp)
42+
if err != nil {
43+
return fmt.Errorf("JsonPut response protocol error: %v, data: %s", err, string(data))
44+
}
45+
}
46+
return nil
47+
}

httpcall/readme.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# http 最常用的 json 协议调用封装
2+
- json_post.go: JsonPost。
3+
- json_get.go: JsonGet。
4+
- json_put.go: JsonPut。
5+
- json_delete.go: JsonDelete。
6+
7+
8+
example: https://github.com/memory-overflow/go-common-library/httpcall/httpcall_test.go
9+
```go
10+
import (
11+
"context"
12+
"testing"
13+
"time"
14+
15+
"github.com/memory-overflow/go-common-library/httpcall"
16+
service "github.com/memory-overflow/go-common-library/task_scheduler/example/add_service"
17+
)
18+
19+
func TestJsonPost(t *testing.T) {
20+
// 控制请求超时时间
21+
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
22+
defer cancel()
23+
uri := "http://127.0.0.1:8000/add"
24+
req := &service.AddRequest{
25+
A: 1,
26+
B: 2,
27+
}
28+
rsp := &service.AddResponse{}
29+
err := httpcall.JsonPost(ctx, uri, nil, req, rsp)
30+
if err != nil {
31+
t.Fatalf("JsonPost err: %v", err)
32+
}
33+
t.Logf("add taskId: %d", rsp.TaskId)
34+
}
35+
```

misc/donwlod.go

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package misc
2+
3+
import (
4+
"context"
5+
"errors"
6+
"fmt"
7+
"io"
8+
"net/http"
9+
"os"
10+
"strconv"
11+
)
12+
13+
// DownloadFile 下载网络文件到服务器本地
14+
func DownloadFile(ctx context.Context, url string, dirs, fileName string) error {
15+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
16+
if err != nil {
17+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
18+
}
19+
res, err := http.DefaultClient.Do(req)
20+
if err != nil {
21+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
22+
}
23+
if res.StatusCode != 200 {
24+
return errors.New("DownloadFile " + url + " failed! " + res.Status)
25+
}
26+
if err := os.MkdirAll(dirs, 0766); err != nil {
27+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
28+
}
29+
filePath := dirs + "/" + fileName
30+
file, err := os.Create(filePath)
31+
if err != nil {
32+
return errors.New("DownloadFile " + url + " create file failed! " + err.Error())
33+
}
34+
if length, err := io.Copy(file, res.Body); err != nil {
35+
os.Remove(filePath)
36+
return errors.New("DownloadFile " + url + " copy failed! " + err.Error() +
37+
" copied length: " + strconv.Itoa(int(length)))
38+
}
39+
file.Close()
40+
_, err = os.Stat(filePath)
41+
if err != nil {
42+
os.Remove(filePath)
43+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
44+
}
45+
return nil
46+
}
47+
48+
// DownloadFileWithLimit 下载网络文件到服务器本地,限制文件大小
49+
func DownloadFileWithLimit(ctx context.Context, url string, dirs, fileName string, maxBytes int64) error {
50+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
51+
if err != nil {
52+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
53+
}
54+
res, err := http.DefaultClient.Do(req)
55+
if err != nil {
56+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
57+
}
58+
if res.StatusCode != 200 {
59+
return errors.New("DownloadFile " + url + " failed! " + res.Status)
60+
}
61+
if err := os.MkdirAll(dirs, 0766); err != nil {
62+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
63+
}
64+
filePath := dirs + "/" + fileName
65+
file, err := os.Create(filePath)
66+
if err != nil {
67+
return errors.New("DownloadFile " + url + " create file failed! " + err.Error())
68+
}
69+
if length, err := io.CopyN(file, res.Body, int64(maxBytes)); err != nil && err != io.EOF {
70+
os.Remove(filePath)
71+
return errors.New("DownloadFile " + url + " copy failed! " + err.Error() +
72+
" copied length: " + strconv.Itoa(int(length)))
73+
}
74+
file.Close()
75+
nextByte := make([]byte, 1)
76+
nRead, _ := io.ReadFull(res.Body, nextByte)
77+
if nRead > 0 {
78+
// Yep, there's too much data
79+
os.Remove(filePath)
80+
return fmt.Errorf("DownloadFile %s exceed the file size limit %d", url, maxBytes)
81+
}
82+
_, err = os.Stat(filePath)
83+
if err != nil {
84+
os.Remove(filePath)
85+
return errors.New("DownloadFile " + url + " failed! " + err.Error())
86+
}
87+
return nil
88+
}

0 commit comments

Comments
 (0)