-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathresponse.go
67 lines (58 loc) · 1.56 KB
/
response.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
package reggie
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"github.com/go-resty/resty/v2"
)
type (
// Response is an HTTP response returned from an OCI registry.
Response struct {
*resty.Response
}
)
// GetRelativeLocation returns the path component of the URL contained
// in the `Location` header of the response.
func (resp *Response) GetRelativeLocation() string {
loc := resp.Header().Get("Location")
u, err := url.Parse(loc)
if err != nil {
return ""
}
path := u.Path
if q := u.RawQuery; q != "" {
path += "?" + q
}
return path
}
// GetAbsoluteLocation returns the full URL, including protocol and host,
// of the location contained in the `Location` header of the response.
func (resp *Response) GetAbsoluteLocation() string {
loc := resp.Header().Get("Location")
_, err := url.Parse(loc)
if err != nil {
return ""
}
return loc
}
// IsUnauthorized returns whether or not the response is a 401
func (resp *Response) IsUnauthorized() bool {
return resp.StatusCode() == http.StatusUnauthorized
}
// Errors attempts to parse a response as OCI-compliant errors array
func (resp *Response) Errors() ([]ErrorInfo, error) {
errorResponse := &ErrorResponse{}
bodyBytes := []byte(resp.String())
err := json.Unmarshal(bodyBytes, errorResponse)
if err != nil {
return nil, err
} else if len(errorResponse.Errors) == 0 {
return nil, errors.New("body was valid json but could not be parsed")
}
errorList := []ErrorInfo{}
for _, errorInfo := range errorResponse.Errors {
errorList = append(errorList, errorInfo)
}
return errorList, nil
}