forked from ewarehousing-solutions/bigcommerce-api-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
79 lines (70 loc) · 1.9 KB
/
client.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
package bigcommerce
import (
"errors"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
)
type Client struct {
StoreHash string `json:"store-hash"`
XAuthToken string `json:"x-auth-token"`
MaxRetries int
HTTPClient HTTPClient
ChannelID int
}
var ErrNoContent = errors.New("no content 204 from BigCommerce API")
var ErrNoMainThumbnail = errors.New("no main thumbnail")
var ErrNotFound = errors.New("404 not found")
// AuthContexter interface for GetAuthContext
type AuthContexter interface {
GetAuthContext(clientID, clientSecret string, q url.Values) (*AuthContext, error)
}
func NewClient(storeHash, xAuthToken string) *Client {
return &Client{
StoreHash: storeHash,
XAuthToken: xAuthToken,
MaxRetries: 1,
HTTPClient: &http.Client{
Timeout: time.Second * 10,
},
ChannelID: 1,
}
}
func (bc *Client) getAPIRequest(method, url string, body io.Reader) *http.Request {
if !strings.HasPrefix(url, "/") {
url = "/" + url
}
fullURL := "https://api.bigcommerce.com/stores/" + bc.StoreHash + url
req, _ := http.NewRequest(method, fullURL, body)
req.Header.Add("X-Auth-Token", bc.XAuthToken)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", "BigCommerce-Go-SDK")
req.Header.Add("Cache-Control", "no-cache")
req.Header.Add("Host", "api.bigcommerce.com")
req.Header.Add("Accept-Encoding", "none")
req.Header.Add("Connection", "keep-alive")
return req
}
func processBody(res *http.Response) ([]byte, error) {
if res.StatusCode == http.StatusNoContent {
return nil, ErrNoContent
}
if res.StatusCode == http.StatusNotFound {
return nil, ErrNotFound
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
res.Body.Close()
if res.StatusCode > 299 {
log.Printf("%s %s %s", res.Request.Method, res.Request.URL, string(body))
return body, errors.New(res.Status)
}
return body, nil
}