ref(client): allow NewRequest to accept multiple types

pull/419/head
Adam Reese 9 years ago
parent c3aaa8b56e
commit 6adaa45cce

@ -17,6 +17,7 @@ limitations under the License.
package client
import (
"bytes"
"encoding/json"
"fmt"
"io"
@ -103,17 +104,24 @@ func (c *Client) Get(endpoint string, v interface{}) (*Response, error) {
return c.Exec(c.NewRequest("GET", endpoint, nil), &v)
}
// Post calls POST on an endpoint and decodes the response
func (c *Client) Post(endpoint string, payload, v interface{}) (*Response, error) {
return c.Exec(c.NewRequest("POST", endpoint, payload), &v)
}
// Delete calls DELETE on an endpoint and decodes the response
func (c *Client) Delete(endpoint string, v interface{}) (*Response, error) {
return c.Exec(c.NewRequest("DELETE", endpoint, nil), &v)
}
// NewRequest creates a new client request
func (c *Client) NewRequest(method, endpoint string, body io.Reader) *Request {
func (c *Client) NewRequest(method, endpoint string, payload interface{}) *Request {
u, err := c.url(endpoint)
if err != nil {
return &Request{err: err}
}
body := prepareBody(payload)
req, err := http.NewRequest(method, u, body)
req.Header.Set("User-Agent", c.agent())
@ -122,6 +130,21 @@ func (c *Client) NewRequest(method, endpoint string, body io.Reader) *Request {
return &Request{req, err}
}
func prepareBody(payload interface{}) io.Reader {
var body io.Reader
switch t := payload.(type) {
default:
//FIXME: panic is only for development
panic(fmt.Sprintf("unexpected type %T\n", t))
case io.Reader:
body = t
case []byte:
body = bytes.NewBuffer(t)
case nil:
}
return body
}
// Exec sends a request and decodes the response
func (c *Client) Exec(req *Request, v interface{}) (*Response, error) {
return c.Result(c.Do(req), &v)

@ -17,7 +17,6 @@ limitations under the License.
package client
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
@ -120,7 +119,6 @@ func (c *Client) PostDeployment(name string, cfg *common.Configuration) error {
}
var out struct{}
b := bytes.NewBuffer(data)
return c.CallService("/deployments", "POST", &out, b)
_, err = c.Post("/deployments", data, &out)
return err
}

Loading…
Cancel
Save