paypale/client.go

69 lines
1.4 KiB
Go
Raw Normal View History

2015-10-15 07:43:50 +02:00
package paypalsdk
import (
2015-10-30 08:02:32 +01:00
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
2015-10-15 07:43:50 +02:00
)
// NewClient returns new Client struct
func NewClient(clientID string, secret string, APIBase string) (*Client, error) {
2015-10-30 08:02:32 +01:00
if clientID == "" || secret == "" || APIBase == "" {
return &Client{}, errors.New("ClientID, Secret and APIBase are required to create a Client")
}
2015-10-15 07:52:16 +02:00
2015-10-30 08:02:32 +01:00
return &Client{
&http.Client{},
clientID,
secret,
APIBase,
nil,
}, nil
2015-10-15 07:43:50 +02:00
}
// Send makes a request to the API, the response body will be
// unmarshaled into v, or if v is an io.Writer, the response will
// be written to it without decoding
func (c *Client) Send(req *http.Request, v interface{}) error {
2015-10-30 08:02:32 +01:00
// Set default headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
2015-10-15 07:43:50 +02:00
2015-10-30 08:02:32 +01:00
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
2015-10-15 07:43:50 +02:00
2015-10-30 08:02:32 +01:00
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
2015-10-15 07:43:50 +02:00
2015-10-30 08:02:32 +01:00
if resp.StatusCode < 200 || resp.StatusCode > 299 {
errResp := &ErrorResponse{Response: resp}
data, err := ioutil.ReadAll(resp.Body)
2015-10-15 07:43:50 +02:00
2015-10-30 08:02:32 +01:00
if err == nil && len(data) > 0 {
json.Unmarshal(data, errResp)
}
2015-10-15 07:43:50 +02:00
2015-10-30 08:02:32 +01:00
return errResp
}
2015-10-15 07:43:50 +02:00
2015-10-30 08:02:32 +01:00
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
return err
}
}
}
2015-10-15 07:43:50 +02:00
2015-10-30 08:02:32 +01:00
return nil
2015-10-15 07:43:50 +02:00
}