2017-12-05 20:44:22 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/ipfs/ipfs-cluster/api"
|
|
|
|
)
|
|
|
|
|
2017-12-08 14:39:30 +00:00
|
|
|
func (c *Client) do(method, path string, body io.Reader, obj interface{}) error {
|
2017-12-05 20:44:22 +00:00
|
|
|
resp, err := c.doRequest(method, path, body)
|
|
|
|
if err != nil {
|
|
|
|
return &api.Error{Code: 0, Message: err.Error()}
|
|
|
|
}
|
|
|
|
return c.handleResponse(resp, obj)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) doRequest(method, path string, body io.Reader) (*http.Response, error) {
|
|
|
|
urlpath := c.urlPrefix + "/" + strings.TrimPrefix(path, "/")
|
|
|
|
logger.Debugf("%s: %s", method, urlpath)
|
|
|
|
|
|
|
|
r, err := http.NewRequest(method, urlpath, body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-12-07 10:27:37 +00:00
|
|
|
if c.config.DisableKeepAlives {
|
|
|
|
r.Close = true
|
|
|
|
}
|
2017-12-05 20:44:22 +00:00
|
|
|
|
|
|
|
if c.config.Username != "" {
|
|
|
|
r.SetBasicAuth(c.config.Username, c.config.Password)
|
|
|
|
}
|
|
|
|
|
2017-12-07 17:47:35 +00:00
|
|
|
return c.client.Do(r)
|
2017-12-05 20:44:22 +00:00
|
|
|
}
|
|
|
|
|
2017-12-08 14:39:30 +00:00
|
|
|
func (c *Client) handleResponse(resp *http.Response, obj interface{}) error {
|
2017-12-05 20:44:22 +00:00
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
2017-12-07 10:27:37 +00:00
|
|
|
resp.Body.Close()
|
|
|
|
|
2017-12-05 20:44:22 +00:00
|
|
|
if err != nil {
|
|
|
|
return &api.Error{Code: resp.StatusCode, Message: err.Error()}
|
|
|
|
}
|
|
|
|
logger.Debugf("Response body: %s", body)
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case resp.StatusCode == http.StatusAccepted:
|
|
|
|
logger.Debug("Request accepted")
|
|
|
|
case resp.StatusCode == http.StatusNoContent:
|
|
|
|
logger.Debug("Request suceeded. Response has no content")
|
|
|
|
default:
|
|
|
|
if resp.StatusCode > 399 {
|
|
|
|
var apiErr api.Error
|
|
|
|
err = json.Unmarshal(body, &apiErr)
|
|
|
|
if err != nil {
|
|
|
|
return &api.Error{
|
|
|
|
Code: resp.StatusCode,
|
|
|
|
Message: err.Error(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return &apiErr
|
|
|
|
}
|
|
|
|
err = json.Unmarshal(body, obj)
|
|
|
|
if err != nil {
|
|
|
|
return &api.Error{
|
|
|
|
Code: resp.StatusCode,
|
|
|
|
Message: err.Error(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|