forked from scaleway/scaleway-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
93 lines (79 loc) · 2.06 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
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
package scw
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"github.com/scaleway/scaleway-sdk-go/internal/auth"
"github.com/scaleway/scaleway-sdk-go/internal/errors"
)
// ScalewayRequest contains all the contents related to performing a request on the Scaleway API.
type ScalewayRequest struct {
Method string
Path string
Headers http.Header
Query url.Values
Body io.Reader
// request options
ctx context.Context
auth auth.Auth
allPages bool
}
// getAllHeaders constructs a http.Header object and aggregates all headers into the object.
func (req *ScalewayRequest) getAllHeaders(token auth.Auth, userAgent string, anonymized bool) http.Header {
var allHeaders http.Header
if anonymized {
allHeaders = token.AnonymizedHeaders()
} else {
allHeaders = token.Headers()
}
allHeaders.Set("User-Agent", userAgent)
if req.Body != nil {
allHeaders.Set("Content-Type", "application/json")
}
for key, value := range req.Headers {
allHeaders.Del(key)
for _, v := range value {
allHeaders.Add(key, v)
}
}
return allHeaders
}
// getURL constructs a URL based on the base url and the client.
func (req *ScalewayRequest) getURL(baseURL string) (*url.URL, SdkError) {
url, err := url.Parse(baseURL + req.Path)
if err != nil {
return nil, errors.New("invalid url %s: %s", baseURL+req.Path, err)
}
url.RawQuery = req.Query.Encode()
return url, nil
}
// SetBody json marshal the given body and write the json content type
// to the request. It also catches when body is a file.
func (req *ScalewayRequest) SetBody(body interface{}) error {
var contentType string
var content io.Reader
switch b := body.(type) {
case *File:
contentType = b.ContentType
content = b.Content
case io.Reader:
contentType = "text/plain"
content = b
default:
buf, err := json.Marshal(body)
if err != nil {
return err
}
contentType = "application/json"
content = bytes.NewReader(buf)
}
if req.Headers == nil {
req.Headers = http.Header{}
}
req.Headers.Set("Content-Type", contentType)
req.Body = content
return nil
}