From c8ae4b6f4237a5e52fcbcda6e7cdf55e5c0f5774 Mon Sep 17 00:00:00 2001 From: Matt Bell <mappum@gmail.com> Date: Tue, 4 Nov 2014 00:11:54 -0800 Subject: [PATCH] commands/http: Decomposed Client#Send function --- commands/http/client.go | 48 ++++++++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/commands/http/client.go b/commands/http/client.go index 4f8dd64ac..b5a647d47 100644 --- a/commands/http/client.go +++ b/commands/http/client.go @@ -41,6 +41,33 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { req.SetOption(cmds.EncLong, cmds.JSON) } + query, in, err := getQuery(req) + if err != nil { + return nil, err + } + + path := strings.Join(req.Path(), "/") + url := fmt.Sprintf(ApiUrlFormat, c.serverAddress, ApiPath, path, query) + + httpRes, err := http.Post(url, "application/octet-stream", in) + if err != nil { + return nil, err + } + + res, err := getResponse(httpRes, req) + if err != nil { + return nil, err + } + + if len(userEncoding) > 0 { + req.SetOption(cmds.EncShort, userEncoding) + req.SetOption(cmds.EncLong, userEncoding) + } + + return res, nil +} + +func getQuery(req cmds.Request) (string, io.Reader, error) { // TODO: handle multiple files with multipart var in io.Reader @@ -64,20 +91,18 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { } else { // TODO: multipart if in != nil { - return nil, fmt.Errorf("Currently, only one file stream is possible per request") + return "", nil, fmt.Errorf("Currently, only one file stream is possible per request") } in = arg.(io.Reader) } } - path := strings.Join(req.Path(), "/") - url := fmt.Sprintf(ApiUrlFormat, c.serverAddress, ApiPath, path, query.Encode()) - - httpRes, err := http.Post(url, "application/octet-stream", in) - if err != nil { - return nil, err - } + return query.Encode(), in, nil +} +// getResponse decodes a http.Response to create a cmds.Response +func getResponse(httpRes *http.Response, req cmds.Request) (cmds.Response, error) { + var err error res := cmds.NewResponse(req) contentType := httpRes.Header["Content-Type"][0] @@ -109,7 +134,6 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { // handle marshalled errors err = dec.Decode(&e) if err != nil { - fmt.Println(err) return nil, err } } @@ -120,17 +144,11 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) { v := req.Command().Type err = dec.Decode(&v) if err != nil { - fmt.Println(err) return nil, err } res.SetOutput(v) } - if len(userEncoding) > 0 { - req.SetOption(cmds.EncShort, userEncoding) - req.SetOption(cmds.EncLong, userEncoding) - } - return res, nil } -- GitLab