-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
65 lines (50 loc) · 1.18 KB
/
request.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
package midjourney
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
type RequestJSONPayload[T any] struct {
JSON T `json:"json"`
}
func (c *Client) Request(ctx context.Context, method string, endpoint Endpoint, payload *[]byte, output any) error {
url := c.APIURL + endpoint
var payloadReq io.Reader
if payload != nil {
payloadReq = bytes.NewReader(*payload)
}
req, err := http.NewRequestWithContext(ctx, method, url, payloadReq)
if err != nil {
return err
}
req.Header.Add("Authorization", c.AuthenticationToken)
req.Header.Add("Content-Type", "application/json")
res, err := c.HTTPClient.Do(req)
if err != nil {
fmt.Printf("err Request: %v\n", err)
return err
}
statusOK := res.StatusCode >= 200 && res.StatusCode < 300
if !statusOK {
body, err := io.ReadAll(res.Body)
if err != nil {
fmt.Printf("Request body err: %v\n", err)
return err
}
fmt.Printf("body: %+v\n", string(body))
return err
}
if output == nil {
return nil
}
body, err := io.ReadAll(res.Body)
if err != nil {
fmt.Printf("Request body err: %v\n", err)
return err
}
// fmt.Printf("body: %+v\n", string(body))
return json.Unmarshal(body, output)
}