forked from zombor/go-ebay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathebay.go
101 lines (78 loc) · 2 KB
/
ebay.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
package ebay
import (
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"github.com/dracoDevs/go-ebay-plus/utils"
)
type EbayConf struct {
baseUrl string
DevId, AppId, CertId string
RuName, AuthToken string
SiteId int
Logger func(...interface{})
}
func (e EbayConf) Sandbox() EbayConf {
e.baseUrl = "https://api.sandbox.ebay.com"
return e
}
func (e EbayConf) Production() EbayConf {
e.baseUrl = "https://api.ebay.com"
return e
}
func (e EbayConf) RunCommand(c Command) (EbayResponse, error) {
ec := ebayRequest{
conf: e,
command: c,
}
body := new(bytes.Buffer)
body.Write([]byte(xml.Header))
err := xml.NewEncoder(body).Encode(ec)
if err != nil {
return ebayResponse{}, err
}
if c.CallName() == "EndItem" {
bodyStr := body.String()
bodyStr = utils.RemoveEndItemXML(bodyStr)
body = bytes.NewBufferString(bodyStr)
}
if e.Logger != nil {
e.Logger(body.String())
}
req, _ := http.NewRequest(
"POST",
fmt.Sprintf("%s/ws/api.dll", e.baseUrl),
body,
)
req.Header.Add("X-EBAY-API-DEV-NAME", e.DevId)
req.Header.Add("X-EBAY-API-APP-NAME", e.AppId)
req.Header.Add("X-EBAY-API-CERT-NAME", e.CertId)
req.Header.Add("X-EBAY-API-CALL-NAME", c.CallName())
req.Header.Add("X-EBAY-API-SITEID", strconv.Itoa(e.SiteId))
req.Header.Add("X-EBAY-API-COMPATIBILITY-LEVEL", strconv.Itoa(837))
req.Header.Add("Content-Type", "text/xml")
client := &http.Client{}
resp, err := client.Do(req)
if urlErr, ok := err.(*url.Error); ok { // TODO: how to unit test this?
return ebayResponse{}, urlErr
} else if resp.StatusCode != 200 {
httpErr := httpError{
statusCode: resp.StatusCode,
}
httpErr.body, _ = ioutil.ReadAll(resp.Body)
return ebayResponse{}, httpErr
}
bodyContents, _ := ioutil.ReadAll(resp.Body)
if e.Logger != nil {
e.Logger(string(bodyContents))
}
response, err := c.ParseResponse(bodyContents)
if response.Failure() {
return response, ebayErrors(response.ResponseErrors())
}
return response, err
}