@cryptotaxi247 / kubo / commits / c8ae4b6f4

commands/http: Decomposed Client#Send function

Matt Bell committed Nov 4, 2014 at 00:11 UTC c8ae4b6f4237a5e52fcbcda6e7cdf55e5c0f5774
1 file changed +33 -15
commands/http/client.go
+33 -15
@@ -41,6 +41,33 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
41 req.SetOption(cmds.EncLong, cmds.JSON)
42 }
43
44 + query, in, err := getQuery(req)
45 + if err != nil {
46 + return nil, err
47 + }
48 +
49 + path := strings.Join(req.Path(), "/")
50 + url := fmt.Sprintf(ApiUrlFormat, c.serverAddress, ApiPath, path, query)
51 +
52 + httpRes, err := http.Post(url, "application/octet-stream", in)
53 + if err != nil {
54 + return nil, err
55 + }
56 +
57 + res, err := getResponse(httpRes, req)
58 + if err != nil {
59 + return nil, err
60 + }
61 +
62 + if len(userEncoding) > 0 {
63 + req.SetOption(cmds.EncShort, userEncoding)
64 + req.SetOption(cmds.EncLong, userEncoding)
65 + }
66 +
67 + return res, nil
68 +}
69 +
70 +func getQuery(req cmds.Request) (string, io.Reader, error) {
71 // TODO: handle multiple files with multipart
72 var in io.Reader
73
@@ -64,20 +91,18 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
91 } else {
92 // TODO: multipart
93 if in != nil {
67 - return nil, fmt.Errorf("Currently, only one file stream is possible per request")
94 + return "", nil, fmt.Errorf("Currently, only one file stream is possible per request")
95 }
96 in = arg.(io.Reader)
97 }
98 }
99
73 - path := strings.Join(req.Path(), "/")
74 - url := fmt.Sprintf(ApiUrlFormat, c.serverAddress, ApiPath, path, query.Encode())
75 -
76 - httpRes, err := http.Post(url, "application/octet-stream", in)
77 - if err != nil {
78 - return nil, err
79 - }
100 + return query.Encode(), in, nil
101 +}
102
103 +// getResponse decodes a http.Response to create a cmds.Response
104 +func getResponse(httpRes *http.Response, req cmds.Request) (cmds.Response, error) {
105 + var err error
106 res := cmds.NewResponse(req)
107
108 contentType := httpRes.Header["Content-Type"][0]
@@ -109,7 +134,6 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
134 // handle marshalled errors
135 err = dec.Decode(&e)
136 if err != nil {
112 - fmt.Println(err)
137 return nil, err
138 }
139 }
@@ -120,17 +144,11 @@ func (c *client) Send(req cmds.Request) (cmds.Response, error) {
144 v := req.Command().Type
145 err = dec.Decode(&v)
146 if err != nil {
123 - fmt.Println(err)
147 return nil, err
148 }
149
150 res.SetOutput(v)
151 }
152
130 - if len(userEncoding) > 0 {
131 - req.SetOption(cmds.EncShort, userEncoding)
132 - req.SetOption(cmds.EncLong, userEncoding)
133 - }
134 -
153 return res, nil
154 }