-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransport.go
50 lines (41 loc) · 1.28 KB
/
transport.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
package anthropic
import (
"errors"
"net/http"
"net/url"
)
// Transport is a http.RoundTripper that includes an API key in each request.
type Transport struct {
APIKey string
}
// NewTransport constructs and returns a new Transport struct that includes the
// given API key as a header in each request.
func NewTransport(apiKey string) *Transport {
return &Transport{APIKey: apiKey}
}
// Client returns an HTTP client that will include the API key in the request,
// and is safe for concurrent use by multiple goroutines.
func (t *Transport) Client() *http.Client {
return &http.Client{
Transport: t,
}
}
// RoundTrip implements the http.RoundTripper interface.
// It makes a copy of the HTTP request so that it complies with the requirements
// of the interface and adds the API key to the new request before calling the
// default http.RoundTripper.
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.APIKey == "" {
return nil, errors.New("API key is required")
}
newReq := new(http.Request)
*newReq = *req
newReq.URL = new(url.URL)
*newReq.URL = *req.URL
newReq.Header = make(http.Header, len(req.Header))
for k, v := range req.Header {
newReq.Header[k] = v
}
newReq.Header.Set("x-api-key", t.APIKey)
return http.DefaultTransport.RoundTrip(newReq)
}