-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfn.go
88 lines (72 loc) · 1.62 KB
/
fn.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
package dify
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
func SendGetRequest(forConsole bool, dc *DifyClient, api string) (httpCode int, bodyText []byte, err error) {
req, err := http.NewRequest("GET", api, nil)
if err != nil {
return -1, nil, err
}
if forConsole {
setConsoleAuthorization(dc, req)
} else {
setAPIAuthorization(dc, req)
}
resp, err := dc.Client.Do(req)
if err != nil {
return -1, nil, err
}
defer resp.Body.Close()
bodyText, err = io.ReadAll(resp.Body)
return resp.StatusCode, bodyText, err
}
func SendPostRequest(forConsole bool, dc *DifyClient, api string, postBody interface{}) (httpCode int, bodyText []byte, err error) {
var payload *strings.Reader
if postBody != nil {
buf, err := json.Marshal(postBody)
if err != nil {
return -1, nil, err
}
payload = strings.NewReader(string(buf))
} else {
payload = nil
}
req, err := http.NewRequest("POST", api, payload)
if err != nil {
return -1, nil, err
}
if forConsole {
setConsoleAuthorization(dc, req)
} else {
setAPIAuthorization(dc, req)
}
resp, err := dc.Client.Do(req)
if err != nil {
return -1, nil, err
}
defer resp.Body.Close()
bodyText, err = io.ReadAll(resp.Body)
return resp.StatusCode, bodyText, err
}
func CommonRiskForSendRequest(code int, err error) error {
if err != nil {
return err
}
if code != http.StatusOK {
return fmt.Errorf("status code: %d", code)
}
return nil
}
func CommonRiskForSendRequestWithCode(code int, err error, targetCode int) error {
if err != nil {
return err
}
if code != targetCode {
return fmt.Errorf("status code: %d", code)
}
return nil
}