ref(client): allow NewRequest to accept multiple types

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

@ -17,6 +17,7 @@ limitations under the License.
package client package client
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@ -103,17 +104,24 @@ func (c *Client) Get(endpoint string, v interface{}) (*Response, error) {
return c.Exec(c.NewRequest("GET", endpoint, nil), &v) 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 // Delete calls DELETE on an endpoint and decodes the response
func (c *Client) Delete(endpoint string, v interface{}) (*Response, error) { func (c *Client) Delete(endpoint string, v interface{}) (*Response, error) {
return c.Exec(c.NewRequest("DELETE", endpoint, nil), &v) return c.Exec(c.NewRequest("DELETE", endpoint, nil), &v)
} }
// NewRequest creates a new client request // 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) u, err := c.url(endpoint)
if err != nil { if err != nil {
return &Request{err: err} return &Request{err: err}
} }
body := prepareBody(payload)
req, err := http.NewRequest(method, u, body) req, err := http.NewRequest(method, u, body)
req.Header.Set("User-Agent", c.agent()) 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} 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 // Exec sends a request and decodes the response
func (c *Client) Exec(req *Request, v interface{}) (*Response, error) { func (c *Client) Exec(req *Request, v interface{}) (*Response, error) {
return c.Result(c.Do(req), &v) return c.Result(c.Do(req), &v)

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

Loading…
Cancel
Save