-
Notifications
You must be signed in to change notification settings - Fork 3
/
net.go
53 lines (44 loc) · 1.32 KB
/
net.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
package inngestgo
import (
"fmt"
"net/http"
)
func fetchWithAuthFallback(
createRequest func() (*http.Request, error),
signingKey string,
signingKeyFallback string,
) (*http.Response, error) {
req, err := createRequest()
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
if signingKey != "" {
key, err := hashedSigningKey([]byte(signingKey))
if err != nil {
return nil, fmt.Errorf("error creating signing key: %w", err)
}
req.Header.Set(HeaderKeyAuthorization, fmt.Sprintf("Bearer %s", string(key)))
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
if (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) && signingKeyFallback != "" {
// Try again with the signing key fallback
req, err := createRequest()
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
_ = resp.Body.Close()
key, err := hashedSigningKey([]byte(signingKeyFallback))
if err != nil {
return nil, fmt.Errorf("error creating signing key: %w", err)
}
req.Header.Set(HeaderKeyAuthorization, fmt.Sprintf("Bearer %s", string(key)))
resp, err = http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
}
return resp, nil
}