forked from stelcheck/ncloud-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
65 lines (50 loc) · 1.52 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
package request
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/anacoondaaa/ncloud-sdk-go/oauth"
)
func encryptHmacSha256(message, secretKey string) string {
h := hmac.New(sha256.New, []byte(secretKey))
h.Write([]byte(message))
sha := h.Sum(nil)
return base64.StdEncoding.EncodeToString(sha)
}
// NewRequest is http request with oauth
func NewRequest(accessKey, secretKey, method, url, urn string, params map[string]string) ([]byte, *http.Response, error) {
c := oauth.NewConsumer(accessKey, secretKey, method, url)
for k, v := range params {
c.AdditionalParams[k] = v
}
now := time.Now()
timestamp := strconv.FormatInt(int64(time.Nanosecond)*now.UnixNano()/int64(time.Millisecond), 10)
reqURL, body, err := c.GetRequest(url + urn)
if err != nil {
return nil, nil, err
}
req, err := http.NewRequest(method, reqURL, body)
if err != nil {
return nil, nil, err
}
message := method + " " + urn + "\n" + timestamp + "\n" + accessKey
apigwSignature := encryptHmacSha256(message, secretKey)
req.Header.Set("x-ncp-iam-access-key", accessKey)
req.Header.Set("x-ncp-apigw-signature-v2", apigwSignature)
req.Header.Set("x-ncp-apigw-timestamp", timestamp)
if method == "POST" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
return bytes, resp, nil
}