forked from jhunt/go-s3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
85 lines (70 loc) · 2 KB
/
http.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
package s3
import (
"bytes"
"fmt"
"net/http"
"regexp"
)
func (c *Client) url(path string) string {
if path == "" || path[0:1] != "/" {
path = "/" + path
}
scheme := c.Protocol
if scheme == "" {
scheme = "https"
}
if c.Bucket == "" {
return fmt.Sprintf("%s://%s%s", scheme, c.domain(), path)
}
if c.UsePathBuckets {
return fmt.Sprintf("%s://%s/%s%s", scheme, c.domain(), c.Bucket, path)
} else {
return fmt.Sprintf("%s://%s.%s%s", scheme, c.Bucket, c.domain(), path)
}
}
func (c *Client) request(method, path string, payload []byte, headers *http.Header) (*http.Response, error) {
in := bytes.NewBuffer(payload)
req, err := http.NewRequest(method, c.url(path), in)
if err != nil {
return nil, err
}
/* copy in any headers */
if headers != nil {
for header, values := range *headers {
for _, value := range values {
req.Header.Add(header, value)
}
}
}
/* sign the request */
req.ContentLength = int64(len(payload))
req.Header.Set("Authorization", c.signature(req, payload))
/* stupid continuation tokens sometimes have literal +'s in them */
req.URL.RawQuery = regexp.MustCompile(`\+`).ReplaceAllString(req.URL.RawQuery, "%2B")
/* optional debugging */
if err := c.traceRequest(req); err != nil {
return nil, err
}
/* submit the request */
res, err := c.ua.Do(req)
if err != nil {
return nil, err
}
/* optional debugging */
if err := c.traceResponse(res); err != nil {
return nil, err
}
return res, nil
}
func (c *Client) post(path string, payload []byte, headers *http.Header) (*http.Response, error) {
return c.request("POST", path, payload, headers)
}
func (c *Client) put(path string, payload []byte, headers *http.Header) (*http.Response, error) {
return c.request("PUT", path, payload, headers)
}
func (c *Client) get(path string, headers *http.Header) (*http.Response, error) {
return c.request("GET", path, nil, headers)
}
func (c *Client) delete(path string, headers *http.Header) (*http.Response, error) {
return c.request("DELETE", path, nil, headers)
}