2015-11-27 12:46:13 +00:00
|
|
|
// Package rest implements a simple REST wrapper
|
2016-02-23 21:16:13 +00:00
|
|
|
//
|
|
|
|
// All methods are safe for concurrent calling.
|
2015-11-27 12:46:13 +00:00
|
|
|
package rest
|
2015-10-04 21:08:31 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
2015-11-27 18:25:52 +00:00
|
|
|
"io/ioutil"
|
2017-07-05 16:48:43 +00:00
|
|
|
"mime/multipart"
|
2015-10-04 21:08:31 +00:00
|
|
|
"net/http"
|
2017-07-06 11:12:01 +00:00
|
|
|
"net/url"
|
2016-02-23 21:16:13 +00:00
|
|
|
"sync"
|
2015-10-04 21:08:31 +00:00
|
|
|
|
|
|
|
"github.com/ncw/rclone/fs"
|
2016-06-12 14:06:02 +00:00
|
|
|
"github.com/pkg/errors"
|
2015-10-04 21:08:31 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Client contains the info to sustain the API
|
|
|
|
type Client struct {
|
2016-02-23 21:16:13 +00:00
|
|
|
mu sync.RWMutex
|
2015-11-27 12:46:13 +00:00
|
|
|
c *http.Client
|
|
|
|
rootURL string
|
|
|
|
errorHandler func(resp *http.Response) error
|
2015-11-27 18:25:52 +00:00
|
|
|
headers map[string]string
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewClient takes an oauth http.Client and makes a new api instance
|
2015-11-27 18:25:52 +00:00
|
|
|
func NewClient(c *http.Client) *Client {
|
|
|
|
api := &Client{
|
2015-11-27 12:46:13 +00:00
|
|
|
c: c,
|
|
|
|
errorHandler: defaultErrorHandler,
|
2015-11-27 18:25:52 +00:00
|
|
|
headers: make(map[string]string),
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
2015-11-27 18:25:52 +00:00
|
|
|
return api
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
|
|
|
|
2017-03-12 11:44:43 +00:00
|
|
|
// ReadBody reads resp.Body into result, closing the body
|
|
|
|
func ReadBody(resp *http.Response) (result []byte, err error) {
|
|
|
|
defer fs.CheckClose(resp.Body, &err)
|
|
|
|
return ioutil.ReadAll(resp.Body)
|
|
|
|
}
|
|
|
|
|
2015-11-27 18:25:52 +00:00
|
|
|
// defaultErrorHandler doesn't attempt to parse the http body, just
|
|
|
|
// returns it in the error message
|
2015-11-27 12:46:13 +00:00
|
|
|
func defaultErrorHandler(resp *http.Response) (err error) {
|
2017-03-12 11:44:43 +00:00
|
|
|
body, err := ReadBody(resp)
|
2015-11-27 18:25:52 +00:00
|
|
|
if err != nil {
|
2017-03-12 11:44:43 +00:00
|
|
|
return errors.Wrap(err, "error reading error out of body")
|
2015-11-27 18:25:52 +00:00
|
|
|
}
|
2016-06-12 14:06:02 +00:00
|
|
|
return errors.Errorf("HTTP error %v (%v) returned body: %q", resp.StatusCode, resp.Status, body)
|
2015-11-27 12:46:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// SetErrorHandler sets the handler to decode an error response when
|
|
|
|
// the HTTP status code is not 2xx. The handler should close resp.Body.
|
2015-11-27 18:25:52 +00:00
|
|
|
func (api *Client) SetErrorHandler(fn func(resp *http.Response) error) *Client {
|
2016-02-23 21:16:13 +00:00
|
|
|
api.mu.Lock()
|
|
|
|
defer api.mu.Unlock()
|
2015-11-27 12:46:13 +00:00
|
|
|
api.errorHandler = fn
|
2015-11-27 18:25:52 +00:00
|
|
|
return api
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetRoot sets the default root URL
|
|
|
|
func (api *Client) SetRoot(RootURL string) *Client {
|
2016-02-23 21:16:13 +00:00
|
|
|
api.mu.Lock()
|
|
|
|
defer api.mu.Unlock()
|
2015-11-27 18:25:52 +00:00
|
|
|
api.rootURL = RootURL
|
|
|
|
return api
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetHeader sets a header for all requests
|
|
|
|
func (api *Client) SetHeader(key, value string) *Client {
|
2016-02-23 21:16:13 +00:00
|
|
|
api.mu.Lock()
|
|
|
|
defer api.mu.Unlock()
|
2015-11-27 18:25:52 +00:00
|
|
|
api.headers[key] = value
|
|
|
|
return api
|
2015-11-27 12:46:13 +00:00
|
|
|
}
|
|
|
|
|
2015-10-04 21:08:31 +00:00
|
|
|
// Opts contains parameters for Call, CallJSON etc
|
|
|
|
type Opts struct {
|
2017-07-05 16:48:43 +00:00
|
|
|
Method string
|
|
|
|
Path string
|
|
|
|
Absolute bool // Path is absolute
|
|
|
|
Body io.Reader
|
|
|
|
NoResponse bool // set to close Body
|
|
|
|
ContentType string
|
|
|
|
ContentLength *int64
|
|
|
|
ContentRange string
|
|
|
|
ExtraHeaders map[string]string
|
|
|
|
UserName string // username for Basic Auth
|
|
|
|
Password string // password for Basic Auth
|
|
|
|
Options []fs.OpenOption
|
2017-07-06 11:12:01 +00:00
|
|
|
IgnoreStatus bool // if set then we don't check error status or parse error body
|
|
|
|
MultipartMetadataName string // set the following 3 vars
|
|
|
|
MultipartContentName string // and Body and pass in request
|
|
|
|
MultipartFileName string // for multipart upload
|
|
|
|
Parameters url.Values // any parameters for the final URL
|
2017-07-05 16:48:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Copy creates a copy of the options
|
|
|
|
func (o *Opts) Copy() *Opts {
|
|
|
|
newOpts := *o
|
|
|
|
return &newOpts
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
|
|
|
|
2015-10-30 08:40:14 +00:00
|
|
|
// DecodeJSON decodes resp.Body into result
|
|
|
|
func DecodeJSON(resp *http.Response, result interface{}) (err error) {
|
2015-11-28 18:13:08 +00:00
|
|
|
defer fs.CheckClose(resp.Body, &err)
|
2015-10-04 21:08:31 +00:00
|
|
|
decoder := json.NewDecoder(resp.Body)
|
|
|
|
return decoder.Decode(result)
|
|
|
|
}
|
|
|
|
|
2016-10-26 17:42:41 +00:00
|
|
|
// ClientWithHeaderReset makes a new http client which resets the
|
|
|
|
// headers passed in on redirect
|
2017-02-25 21:41:03 +00:00
|
|
|
//
|
|
|
|
// FIXME This is now unecessary with go1.8
|
2016-10-26 17:42:41 +00:00
|
|
|
func ClientWithHeaderReset(c *http.Client, headers map[string]string) *http.Client {
|
2016-09-10 10:29:57 +00:00
|
|
|
if len(headers) == 0 {
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
clientCopy := *c
|
|
|
|
clientCopy.CheckRedirect = func(req *http.Request, via []*http.Request) error {
|
|
|
|
if len(via) >= 10 {
|
|
|
|
return errors.New("stopped after 10 redirects")
|
|
|
|
}
|
|
|
|
// Reset the headers in the new request
|
|
|
|
for k, v := range headers {
|
|
|
|
if v != "" {
|
2017-02-25 21:41:03 +00:00
|
|
|
req.Header.Set(k, v)
|
2016-09-10 10:29:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return &clientCopy
|
|
|
|
}
|
|
|
|
|
2015-10-04 21:08:31 +00:00
|
|
|
// Call makes the call and returns the http.Response
|
|
|
|
//
|
|
|
|
// if err != nil then resp.Body will need to be closed
|
|
|
|
//
|
|
|
|
// it will return resp if at all possible, even if err is set
|
|
|
|
func (api *Client) Call(opts *Opts) (resp *http.Response, err error) {
|
2016-02-23 21:16:13 +00:00
|
|
|
api.mu.RLock()
|
|
|
|
defer api.mu.RUnlock()
|
2015-10-04 21:08:31 +00:00
|
|
|
if opts == nil {
|
2016-06-12 14:06:02 +00:00
|
|
|
return nil, errors.New("call() called with nil opts")
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
|
|
|
var url string
|
|
|
|
if opts.Absolute {
|
|
|
|
url = opts.Path
|
|
|
|
} else {
|
2015-11-27 18:25:52 +00:00
|
|
|
if api.rootURL == "" {
|
2016-06-12 14:06:02 +00:00
|
|
|
return nil, errors.New("RootURL not set")
|
2015-11-27 18:25:52 +00:00
|
|
|
}
|
2015-11-27 12:46:13 +00:00
|
|
|
url = api.rootURL + opts.Path
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
2017-07-06 11:12:01 +00:00
|
|
|
if opts.Parameters != nil && len(opts.Parameters) > 0 {
|
|
|
|
url += "?" + opts.Parameters.Encode()
|
|
|
|
}
|
2015-10-04 21:08:31 +00:00
|
|
|
req, err := http.NewRequest(opts.Method, url, opts.Body)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2015-11-27 18:25:52 +00:00
|
|
|
headers := make(map[string]string)
|
|
|
|
// Set default headers
|
|
|
|
for k, v := range api.headers {
|
|
|
|
headers[k] = v
|
|
|
|
}
|
2015-10-04 21:08:31 +00:00
|
|
|
if opts.ContentType != "" {
|
2015-11-27 18:25:52 +00:00
|
|
|
headers["Content-Type"] = opts.ContentType
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
|
|
|
if opts.ContentLength != nil {
|
|
|
|
req.ContentLength = *opts.ContentLength
|
|
|
|
}
|
|
|
|
if opts.ContentRange != "" {
|
2015-11-27 18:25:52 +00:00
|
|
|
headers["Content-Range"] = opts.ContentRange
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
2015-11-27 18:25:52 +00:00
|
|
|
// Set any extra headers
|
2015-10-30 08:40:14 +00:00
|
|
|
if opts.ExtraHeaders != nil {
|
|
|
|
for k, v := range opts.ExtraHeaders {
|
2015-11-27 18:25:52 +00:00
|
|
|
headers[k] = v
|
2015-10-30 08:40:14 +00:00
|
|
|
}
|
|
|
|
}
|
2016-09-10 10:29:57 +00:00
|
|
|
// add any options to the headers
|
|
|
|
fs.OpenOptionAddHeaders(opts.Options, headers)
|
2015-11-27 18:25:52 +00:00
|
|
|
// Now set the headers
|
|
|
|
for k, v := range headers {
|
2016-02-23 21:16:13 +00:00
|
|
|
if v != "" {
|
|
|
|
req.Header.Add(k, v)
|
|
|
|
}
|
2015-11-27 18:25:52 +00:00
|
|
|
}
|
|
|
|
if opts.UserName != "" || opts.Password != "" {
|
|
|
|
req.SetBasicAuth(opts.UserName, opts.Password)
|
|
|
|
}
|
2016-10-26 17:42:41 +00:00
|
|
|
c := ClientWithHeaderReset(api.c, headers)
|
2016-02-23 21:16:13 +00:00
|
|
|
api.mu.RUnlock()
|
2016-09-10 10:29:57 +00:00
|
|
|
resp, err = c.Do(req)
|
2016-02-23 21:16:13 +00:00
|
|
|
api.mu.RLock()
|
2015-10-04 21:08:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-03-12 11:44:43 +00:00
|
|
|
if !opts.IgnoreStatus {
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
|
|
|
return resp, api.errorHandler(resp)
|
|
|
|
}
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
|
|
|
if opts.NoResponse {
|
|
|
|
return resp, resp.Body.Close()
|
|
|
|
}
|
|
|
|
return resp, nil
|
|
|
|
}
|
|
|
|
|
2015-10-30 08:40:14 +00:00
|
|
|
// CallJSON runs Call and decodes the body as a JSON object into response (if not nil)
|
2015-10-04 21:08:31 +00:00
|
|
|
//
|
|
|
|
// If request is not nil then it will be JSON encoded as the body of the request
|
|
|
|
//
|
|
|
|
// It will return resp if at all possible, even if err is set
|
|
|
|
func (api *Client) CallJSON(opts *Opts, request interface{}, response interface{}) (resp *http.Response, err error) {
|
2017-07-05 16:48:43 +00:00
|
|
|
var requestBody []byte
|
|
|
|
// Marshal the request if given
|
|
|
|
if request != nil {
|
|
|
|
opts = opts.Copy()
|
|
|
|
requestBody, err = json.Marshal(request)
|
|
|
|
opts.ContentType = "application/json"
|
2015-10-04 21:08:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-07-05 16:48:43 +00:00
|
|
|
// Set the body up as a JSON object if required
|
|
|
|
if opts.Body == nil {
|
|
|
|
opts.Body = bytes.NewBuffer(requestBody)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
errChan := make(chan error, 1)
|
|
|
|
isMultipart := opts.MultipartMetadataName != "" && opts.Body != nil && request != nil
|
|
|
|
if isMultipart {
|
|
|
|
bodyReader, bodyWriter := io.Pipe()
|
|
|
|
writer := multipart.NewWriter(bodyWriter)
|
|
|
|
opts.ContentType = writer.FormDataContentType()
|
|
|
|
in := opts.Body
|
|
|
|
opts.Body = bodyReader
|
|
|
|
go func() {
|
|
|
|
defer func() { _ = bodyWriter.Close() }()
|
|
|
|
var err error
|
|
|
|
|
|
|
|
// Create the first part
|
|
|
|
err = writer.WriteField(opts.MultipartMetadataName, string(requestBody))
|
|
|
|
if err != nil {
|
|
|
|
errChan <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add the file part
|
|
|
|
part, err := writer.CreateFormFile(opts.MultipartContentName, opts.MultipartFileName)
|
|
|
|
if err != nil {
|
|
|
|
errChan <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Copy it in
|
|
|
|
if _, err := io.Copy(part, in); err != nil {
|
|
|
|
errChan <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
errChan <- writer.Close()
|
|
|
|
}()
|
2015-10-04 21:08:31 +00:00
|
|
|
}
|
|
|
|
resp, err = api.Call(opts)
|
|
|
|
if err != nil {
|
|
|
|
return resp, err
|
|
|
|
}
|
2015-11-27 18:25:52 +00:00
|
|
|
if response == nil || opts.NoResponse {
|
2015-10-30 08:40:14 +00:00
|
|
|
return resp, nil
|
|
|
|
}
|
2017-07-05 16:48:43 +00:00
|
|
|
if isMultipart {
|
|
|
|
err = <-errChan
|
|
|
|
if err != nil {
|
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
}
|
2015-10-30 08:40:14 +00:00
|
|
|
err = DecodeJSON(resp, response)
|
2015-10-04 21:08:31 +00:00
|
|
|
return resp, err
|
|
|
|
}
|