-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathclient.go
123 lines (106 loc) · 2.51 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package dify
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strings"
)
type Client struct {
host string
apiSecretKey string
httpClient *http.Client
httpRequest *http.Request
}
func NewClientWithConfig(c *ClientConfig) *Client {
var httpClient = &http.Client{}
if c.Timeout == 0 {
httpClient.Timeout = c.Timeout
}
if c.Transport != nil {
httpClient.Transport = c.Transport
}
return &Client{
host: c.Host,
apiSecretKey: c.ApiSecretKey,
httpClient: httpClient,
}
}
func NewClient(host, apiSecretKey string) *Client {
return NewClientWithConfig(&ClientConfig{
Host: host,
ApiSecretKey: apiSecretKey,
})
}
func (c *Client) NewHttpRequest(ctx context.Context, method, requestUrl string, request ...interface{}) (r *http.Request, err error) {
if method == http.MethodGet {
if len(request) > 0 {
if urlValues, ok := request[0].(url.Values); ok {
var requestUrlParse *url.URL
if requestUrlParse, err = url.Parse(requestUrl); err != nil {
return
}
requestUrlParse.RawQuery = urlValues.Encode()
requestUrl = requestUrlParse.String()
}
}
r, err = http.NewRequestWithContext(ctx, method, requestUrl, http.NoBody)
} else if method == http.MethodPost {
var b io.Reader
if len(request) > 0 {
var reqBytes []byte
if reqBytes, err = json.Marshal(request[0]); err != nil {
return
}
b = bytes.NewBuffer(reqBytes)
} else {
b = http.NoBody
}
r, err = http.NewRequestWithContext(ctx, method, requestUrl, b)
} else {
err = errors.New("NewHttpRequest.method must be http.MethodGet or http.MethodPost")
}
return
}
func (c *Client) SetHttpRequest(r *http.Request) *Client {
c.httpRequest = r
return c
}
func (c *Client) SetHttpRequestHeader(key string, value string) *Client {
c.httpRequest.Header.Set(key, value)
return c
}
func (c *Client) SendRequest(res interface{}) (err error) {
if c.httpRequest == nil {
panic("http_request illegal")
}
var resp *http.Response
if resp, err = c.httpClient.Do(c.httpRequest); err != nil {
return
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(res)
return
}
func (c *Client) SendRequestStream() (resp *http.Response, err error) {
if c.httpRequest == nil {
panic("http_request illegal")
}
resp, err = c.httpClient.Do(c.httpRequest)
return
}
func (c *Client) GetHost() string {
var host = strings.TrimSuffix(c.host, "/")
return host
}
func (c *Client) GetApiSecretKey() string {
return c.apiSecretKey
}
func (c *Client) Api() *Api {
return &Api{
c: c,
}
}