-
Notifications
You must be signed in to change notification settings - Fork 0
/
together.go
118 lines (97 loc) · 2.7 KB
/
together.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
package together
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"regexp"
"strconv"
"time"
"github.com/hashicorp/go-retryablehttp"
)
const (
defaultScheme = "https"
defaultHostname = "api.together.xyz"
defaultBasePath = "/"
defaultRetries = 5
userAgent = "together-go"
errEmptyAPIToken = "invalid credentials: API Token must not be empty" //nolint:gosec,unused
)
var (
Version string = "v1" // This corresponds to the version of the API and is used in the URL path
)
type API struct {
APIKey string
BaseURL string
UserAgent string
headers http.Header
Client *retryablehttp.Client
Debug bool
}
func New(key string) (*API, error) {
if key == "" {
return nil, errors.New(errEmptyAPIToken)
}
api := &API{}
api.BaseURL = fmt.Sprintf("%s://%s", defaultScheme, defaultHostname)
api.Client = retryablehttp.NewClient()
api.Client.RetryMax = defaultRetries
api.Debug = false
api.APIKey = key
api.UserAgent = userAgent + "/" + Version + " (" + strconv.FormatInt(time.Now().UnixNano(), 36) + ")"
return api, nil
}
func (api *API) request(ctx context.Context, method, uri string, reqBody io.Reader, headers http.Header) (*http.Response, error) {
req, err := retryablehttp.NewRequestWithContext(ctx, method, api.BaseURL+uri, reqBody)
if err != nil {
return nil, fmt.Errorf("HTTP request creation failed: %w", err)
}
combinedHeaders := make(http.Header)
copyHeader(combinedHeaders, api.headers)
copyHeader(combinedHeaders, headers)
req.Header = combinedHeaders
req.Header.Set("Authorization", "Bearer "+api.APIKey)
if api.UserAgent != "" {
req.Header.Set("User-Agent", api.UserAgent)
}
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
if api.Debug {
dump, err := httputil.DumpRequestOut(req.Request, true)
if err != nil {
return nil, err
}
// Strip out any sensitive information from the request payload.
sensitiveKeys := []string{api.APIKey}
for _, key := range sensitiveKeys {
if key != "" {
valueRegex := regexp.MustCompile(fmt.Sprintf("(?m)%s", key))
dump = valueRegex.ReplaceAll(dump, []byte("[redacted]"))
}
}
log.Printf("\n%s", string(dump))
}
resp, err := api.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("HTTP request failed: %w", err)
}
if api.Debug {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return resp, err
}
log.Printf("\n%s", string(dump))
}
return resp, nil
}
// copyHeader copies all headers for `source` and sets them on `target`.
// based on https://godoc.org/github.com/golang/gddo/httputil/header#Copy
func copyHeader(target, source http.Header) {
for k, vs := range source {
target[k] = vs
}
}