Skip to content

Commit 3410c1f

Browse files
author
lixizan
committed
merge dev into master
2 parents 4d02f44 + aba53f7 commit 3410c1f

File tree

18 files changed

+537
-713
lines changed

18 files changed

+537
-713
lines changed

.github/workflows/go.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ jobs:
1919
- name: Set up Go
2020
uses: actions/setup-go@v3
2121
with:
22-
go-version: 1.16
22+
go-version: 1.18
2323

2424
- name: Test
25-
run: go test
25+
run: go test ./...

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@
1515
test/
1616
debug
1717
vendor/
18-
examples/
18+
examples/
19+
bin/

Makefile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
test:
2+
go test -count 1 -timeout 30s -run ^Test ./...
3+
4+
bench:
5+
go test -benchmem -run=^$$ -bench . github.com/lxzan/gws
6+
7+
cover:
8+
go test -coverprofile=./bin/cover.out --cover ./...

README.md

Lines changed: 83 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -1,165 +1,132 @@
11
# Hasaki
2+
23
http request library for golang
34

4-
[![Build Status](https://github.com/lxzan/hasaki/workflows/Go%20Test/badge.svg?branch=master)](https://github.com/lxzan/hasaki/actions?query=branch%3Amaster)
5-
[![OSCS Status](https://www.oscs1024.com/platform/badge/lxzan/hasaki.svg?size=small)](https://www.oscs1024.com/project/lxzan/hasaki?ref=badge_small)
5+
[![Build Status][1]][2] [![codecov][3]][4]
66

7-
- Package
8-
```bash
9-
github.com/lxzan/hasaki
10-
```
7+
[1]: https://github.com/lxzan/hasaki/workflows/Go%20Test/badge.svg?branch=master
118

12-
### 基本使用
13-
#### 发送GET请求
14-
```go
15-
package main
9+
[2]: https://github.com/lxzan/hasaki/actions?query=branch%3Amaster
1610

17-
import (
18-
"github.com/lxzan/hasaki"
19-
)
11+
[3]: https://codecov.io/gh/lxzan/hasaki/graph/badge.svg?token=0VY55RLS3G
2012

21-
func main() {
22-
result := make([]map[string]interface{}, 0)
23-
err := hasaki.
24-
Get("https://api.github.com/users/%s/repos", "lxzan").
25-
SetQuery(hasaki.Any{
26-
"type": "go",
27-
"per_page": 1,
28-
}).
29-
Send(nil).
30-
BindJSON(&result)
31-
}
32-
```
13+
[4]: https://codecov.io/gh/lxzan/hasaki
3314

34-
#### 发送POST JSON请求
35-
```go
36-
func main() {
37-
var body = struct {
38-
Name string `json:"name"`
39-
}{Name: "caster"}
40-
41-
err := hasaki.
42-
Post("http://localhost:8080" + "/sendJson").
43-
SetEncoder(hasaki.JsonEncoder).
44-
Send(body).
45-
Err()
46-
}
47-
```
15+
- [Hasaki](#hasaki)
16+
- [Features](#features)
17+
- [Install](#install)
18+
- [Usage](#usage)
19+
- [GET](#get)
20+
- [POST](#post)
21+
- [Middleware](#middleware)
4822

49-
#### 发送POST Form请求
50-
```go
51-
func main() {
52-
var body = struct {
53-
Name string `form:"name"`
54-
}{Name: "caster"}
23+
### Features
5524

56-
// Content-Type: application/x-www-form-urlencoded
57-
err := hasaki.
58-
Post("http://localhost:8080" + "/sendForm").
59-
SetEncoder(hasaki.FormEncoder).
60-
Send(body).
61-
Err()
62-
}
25+
- [x] Buffer Pool
26+
- [x] Trace the Error Stack
27+
- [x] JSON / WWWForm Encoder
28+
- [x] Request Before and After Middleware
29+
30+
### Install
31+
32+
```bash
33+
go get -v github.com/lxzan/hasaki
6334
```
6435

65-
#### 发送字节流
36+
### Usage
37+
38+
##### GET
39+
6640
```go
6741
package main
6842

6943
import (
44+
"log"
45+
7046
"github.com/lxzan/hasaki"
71-
"os"
7247
)
7348

7449
func main() {
75-
file, _ := os.Open("")
76-
err := hasaki.
77-
Put("http://localhost:8080" + "/upload").
78-
SetHeader(hasaki.H{"Content-Type": hasaki.ContentTypeSTREAM}).
79-
Send(file).
80-
Err()
50+
type Query struct {
51+
Q string `form:"q"`
52+
Page int `form:"page"`
53+
Order string `form:"-"`
54+
}
55+
var out = make(map[string]any)
56+
var err = hasaki.
57+
Get("https://api.github.com/search/repositories").
58+
SetQuery(Query{
59+
Q: "go-ws",
60+
Page: 1,
61+
}).
62+
Send(nil).
63+
BindJSON(out)
64+
if err != nil {
65+
log.Printf("%+v", err)
66+
}
8167
}
82-
```
83-
84-
### 高级
8568

86-
#### 设置代理
87-
```go
88-
cli, err := hasaki.NewClient(hasaki.WithProxy("socks5://127.0.0.1:1080"))
8969
```
9070

91-
#### 统一的错误处理
71+
##### POST
72+
9273
```go
9374
package main
9475

9576
import (
96-
"context"
97-
"fmt"
98-
jsoniter "github.com/json-iterator/go"
77+
"log"
78+
9979
"github.com/lxzan/hasaki"
100-
"github.com/pkg/errors"
101-
"mime"
102-
"net/http"
10380
)
10481

105-
type BaseResult struct {
106-
Code *int `json:"code"`
107-
Message string `json:"message"`
108-
}
109-
110-
var afterFunc = func(ctx context.Context, resp *http.Response) (context.Context, error) {
111-
if resp.StatusCode != http.StatusOK {
112-
return ctx, hasaki.ErrUnexpectedStatusCode
113-
}
114-
typ, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
115-
if typ != "application/json" {
116-
return ctx, nil
82+
func main() {
83+
type Query struct {
84+
Q string `form:"q"`
85+
Page int `form:"page"`
86+
Order string `form:"-"`
11787
}
118-
119-
rc, err := hasaki.NewReadCloser(resp.Body)
88+
var out = make(map[string]any)
89+
var err = hasaki.
90+
Post("https://api.github.com/search/repositories").
91+
SetEncoder(hasaki.FormEncoder).
92+
Send(Query{
93+
Q: "go-ws",
94+
Page: 1,
95+
}).
96+
BindJSON(&out)
12097
if err != nil {
121-
return ctx, err
122-
}
123-
var result = BaseResult{}
124-
if err := jsoniter.Unmarshal(rc.Bytes(), &result); err != nil {
125-
return ctx, err
126-
}
127-
if result.Code == nil || *result.Code != 0 {
128-
return ctx, errors.New(result.Message)
98+
log.Printf("%+v", err)
12999
}
130-
resp.Body = rc
131-
return ctx, nil
132-
}
133-
134-
func main() {
135-
cli, _ := hasaki.NewClient(hasaki.WithAfter(afterFunc))
136100
}
137101
```
138102

139-
#### 统计请求耗时
103+
### Middleware
104+
140105
```go
141106
package main
142107

143108
import (
144109
"context"
145-
"fmt"
146-
"github.com/lxzan/hasaki"
110+
"log"
147111
"net/http"
148112
"time"
113+
114+
"github.com/lxzan/hasaki"
149115
)
150116

151117
func main() {
152-
cli, _ := hasaki.NewClient(
153-
hasaki.WithBefore(func(ctx context.Context, request *http.Request) (context.Context, error) {
154-
ctx = context.WithValue(ctx, "t0", time.Now())
155-
return ctx, nil
156-
}),
157-
hasaki.WithAfter(func(ctx context.Context, response *http.Response) (context.Context, error) {
158-
t0 := ctx.Value("t0").(time.Time)
159-
fmt.Printf("cost = %dms\n", time.Since(t0).Milliseconds())
160-
return ctx, nil
161-
}),
162-
)
163-
cli.Get("https://api.github.com/users/%s", "lxzan").Send(nil)
118+
before := hasaki.WithBefore(func(ctx context.Context, request *http.Request) (context.Context, error) {
119+
return context.WithValue(ctx, "t0", time.Now()), nil
120+
})
121+
122+
after := hasaki.WithAfter(func(ctx context.Context, response *http.Response) (context.Context, error) {
123+
t0 := ctx.Value("t0").(time.Time)
124+
log.Printf("latency=%s", time.Since(t0).String())
125+
return ctx, nil
126+
})
127+
128+
var url = "https://api.github.com/search/repositories"
129+
cli, _ := hasaki.NewClient(before, after)
130+
cli.Get(url).Send(nil)
164131
}
165132
```

client.go

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,17 @@ import (
44
"context"
55
"fmt"
66
"net/http"
7+
"strings"
78
)
89

910
type Client struct {
10-
config *Config
11+
config *config
1112
}
1213

13-
// NewClient 新建一个客户端, 支持自定义HttpClient, 错误检查和中间件
14+
// NewClient 新建一个客户端
15+
// Create a new client
1416
func NewClient(options ...Option) (*Client, error) {
15-
var c = new(Config)
17+
var c = new(config)
1618
options = append(options, withInitialize())
1719
for _, f := range options {
1820
f(c)
@@ -21,34 +23,33 @@ func NewClient(options ...Option) (*Client, error) {
2123
return client, nil
2224
}
2325

24-
func (c *Client) Get(url string, args ...interface{}) *Request {
26+
func (c *Client) Get(url string, args ...any) *Request {
2527
return c.Request(http.MethodGet, url, args...)
2628
}
2729

28-
func (c *Client) Post(url string, args ...interface{}) *Request {
30+
func (c *Client) Post(url string, args ...any) *Request {
2931
return c.Request(http.MethodPost, url, args...)
3032
}
3133

32-
func (c *Client) Put(url string, args ...interface{}) *Request {
34+
func (c *Client) Put(url string, args ...any) *Request {
3335
return c.Request(http.MethodPut, url, args...)
3436
}
3537

36-
func (c *Client) Delete(url string, args ...interface{}) *Request {
38+
func (c *Client) Delete(url string, args ...any) *Request {
3739
return c.Request(http.MethodDelete, url, args...)
3840
}
3941

40-
func (c *Client) Request(method string, url string, args ...interface{}) *Request {
42+
func (c *Client) Request(method string, url string, args ...any) *Request {
4143
if len(args) > 0 {
4244
url = fmt.Sprintf(url, args...)
4345
}
44-
return &Request{
46+
return (&Request{
4547
ctx: context.Background(),
4648
client: c.config.HTTPClient,
47-
method: method,
49+
method: strings.ToUpper(method),
4850
url: url,
49-
encoder: JsonEncoder,
5051
before: c.config.BeforeFunc,
5152
after: c.config.AfterFunc,
5253
headers: http.Header{},
53-
}
54+
}).SetEncoder(JsonEncoder)
5455
}

0 commit comments

Comments
 (0)