forked from sunny0826/go-chatglm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_client.go
82 lines (70 loc) · 1.96 KB
/
http_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
package chatglm
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/go-resty/resty/v2"
)
var headers = map[string]string{
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8",
}
func post(apiURL, token string, params map[string]interface{}, timeout time.Duration) (map[string]interface{}, error) {
client := resty.New()
client.SetTimeout(timeout)
resp, err := client.R().
SetHeaders(headers).
SetHeader("Authorization", token).
SetBody(params).
Post(apiURL)
if err != nil {
return nil, fmt.Errorf("请求异常:%w", err)
}
if resp.StatusCode() != http.StatusOK {
return nil, fmt.Errorf("响应异常:%s", resp.Body())
}
var result map[string]interface{}
err = json.Unmarshal(resp.Body(), &result)
if err != nil {
return nil, fmt.Errorf("JSON 解析异常:%w", err)
}
return result, nil
}
func stream(apiURL, token string, params map[string]interface{}, timeout time.Duration) (*resty.Response, error) {
client := resty.New()
client.SetTimeout(timeout)
resp, err := client.R().
SetHeader("Accept", "text/event-stream").
SetHeader("Authorization", token).
SetQueryParam("stream", "true").
SetBody(params).
Post(apiURL)
if err != nil {
return nil, fmt.Errorf("请求异常:%w", err)
}
if resp.StatusCode() != http.StatusOK {
return nil, fmt.Errorf("响应异常:%s", resp.Body())
}
return resp, nil
}
func get(apiURL, token string, timeout time.Duration) (map[string]interface{}, error) {
client := resty.New()
client.SetTimeout(timeout)
resp, err := client.R().
SetHeaders(headers).
SetHeader("Authorization", token).
Get(apiURL)
if err != nil {
return nil, fmt.Errorf("请求异常:%w", err)
}
if resp.StatusCode() != http.StatusOK {
return nil, fmt.Errorf("响应异常:%s", resp.Body())
}
var result map[string]interface{}
err = json.Unmarshal(resp.Body(), &result)
if err != nil {
return nil, fmt.Errorf("JSON 解析异常:%w", err)
}
return result, nil
}