-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
helper.go
51 lines (41 loc) · 966 Bytes
/
helper.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
package nlp
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type helper interface {
sendRequest(method, url string, body io.Reader, payload interface{}, headers map[string]string) error
}
var _ helper = &help{}
type help struct {
apiKey string
httpClient http.Client
}
func (h *help) sendRequest(method, url string, body io.Reader, payload interface{}, headers map[string]string) error {
req, err := http.NewRequest(method, url, body)
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", h.apiKey))
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := h.httpClient.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("nlp: %s", body)
}
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&payload); err != nil {
return err
}
return nil
}