commands/http: Made HTTP client unmarshal response values based on the Command#Type
Matt Bell committed
Oct 28, 2014 at 22:19 UTC
c0a9871d4815c374be7588022fa4846bb71dafdf
1 file changed
+19
-9
commands/http/client.go
+19
-9
@@ -1,8 +1,8 @@
1
package http
2
3
import (
4
- //"encoding/json"
5
- //"fmt"
4
+ "encoding/json"
5
+ "fmt"
6
"net/http"
7
"strings"
8
@@ -28,6 +28,16 @@ func Send(req cmds.Request) (cmds.Response, error) {
28
url := "http://" + host + ApiPath
29
url += "/" + strings.Join(req.Path(), "/")
30
31
+ var userEncoding string
32
+ if enc, found := req.Option(cmds.EncShort); found {
33
+ userEncoding = enc.(string)
34
+ req.SetOption(cmds.EncShort, cmds.JSON)
35
+ } else {
36
+ enc, _ := req.Option(cmds.EncLong)
37
+ userEncoding = enc.(string)
38
+ req.SetOption(cmds.EncLong, cmds.JSON)
39
+ }
40
+
41
query := "?"
42
for k, v := range req.Options() {
43
query += "&" + k + "=" + v.(string)
@@ -41,11 +51,7 @@ func Send(req cmds.Request) (cmds.Response, error) {
51
return nil, err
52
}
53
44
- // commented out: code to parse HTTP response and turn it into a cmds.Response
45
- // for now, we are simply reading the data as a stream
54
res := cmds.NewResponse(req)
47
- res.SetValue(httpRes.Body)
48
- /*res := cmds.NewResponse(req)
55
56
contentType := httpRes.Header["Content-Type"][0]
57
contentType = strings.Split(contentType, ";")[0]
@@ -55,7 +61,6 @@ func Send(req cmds.Request) (cmds.Response, error) {
61
return res, nil
62
}
63
58
- // TODO: decode based on `encoding`, using multicodec
64
dec := json.NewDecoder(httpRes.Body)
65
66
if httpRes.StatusCode >= http.StatusBadRequest {
@@ -69,7 +74,7 @@ func Send(req cmds.Request) (cmds.Response, error) {
74
res.SetError(e, e.Code)
75
76
} else {
72
- var v interface{}
77
+ v := req.Command().Type
78
err = dec.Decode(&v)
79
if err != nil {
80
fmt.Println(err)
@@ -77,7 +82,12 @@ func Send(req cmds.Request) (cmds.Response, error) {
82
}
83
84
res.SetValue(v)
80
- }*/
85
+ }
86
+
87
+ if len(userEncoding) > 0 {
88
+ req.SetOption(cmds.EncShort, userEncoding)
89
+ req.SetOption(cmds.EncLong, userEncoding)
90
+ }
91
92
return res, nil
93
}