-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
108 lines (92 loc) · 2.28 KB
/
session.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package shopgun
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
// Session request
type Session struct {
APIKey string `json:"api_key"`
}
// SessionResponse response
type SessionResponse struct {
Token string `json:"token"`
Reference string `json:"reference"`
Expires Time `json:"expires"`
User interface{} `json:"user"`
Permissions struct {
Guest []string `json:"guest"`
} `json:"permissions"`
Provider interface{} `json:"provider"`
ClientID string `json:"client_id"`
}
func (c *Client) session() (SessionResponse, error) {
if c.sr.Token != "" && !c.sr.Expires.After(time.Now()) {
return c.sr, nil
}
path := fmt.Sprintf("%v/sessions", c.basePath)
data, err := json.Marshal(&Session{c.apiKey})
if err != nil {
return SessionResponse{}, err
}
body := bytes.NewReader(data)
req, err := http.NewRequest("POST", path, body)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.c.Do(req)
if err != nil {
return SessionResponse{}, err
}
if resp.StatusCode > 299 {
respBody, _ := ioutil.ReadAll(resp.Body)
log.Print(string(respBody))
return SessionResponse{}, errors.New("got error: %v" + resp.Status)
}
var sr SessionResponse
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&sr)
if err != nil {
return SessionResponse{}, err
}
c.sr = sr
return sr, nil
}
func (c *Client) doGet(path string, out interface{}) error {
path = fmt.Sprintf("%v%v", c.basePath, path)
req, err := http.NewRequest("GET", path, nil)
if err != nil {
return err
}
sr, err := c.session()
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Token", sr.Token)
// Sign request.
sign := sha256.New()
sign.Write([]byte(c.secret + sr.Token))
sum := sign.Sum(nil)
req.Header.Set("X-Signature", fmt.Sprintf("%x", sum))
resp, err := c.c.Do(req)
if err != nil {
return err
}
//TODO: Keep an eye on X-RateLimit
body, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode > 299 {
return fmt.Errorf("Shopgun returned: %v, Body: %v", resp.Status, body)
}
err = json.Unmarshal(body, out)
if err != nil {
return err
}
return nil
}