@cryptotaxi247 / kubo / commits / 8b61daa1d

commands/http: Moved HTTP RPC into commands/http package

Matt Bell committed Oct 24, 2014 at 14:16 UTC 8b61daa1dbd23f5244e4631e5e2a621a84367c66
1 file changed +70
commands/http/client.go new
+70
@@ -0,0 +1,70 @@
1 +package http
2 +
3 +import (
4 + "encoding/json"
5 + "fmt"
6 + "net/http"
7 + "strings"
8 +
9 + cmds "github.com/jbenet/go-ipfs/commands"
10 +)
11 +
12 +const ApiPath = "/api/v0"
13 +
14 +func Send(req cmds.Request) (cmds.Response, error) {
15 + // TODO: load RPC host from config
16 + url := "http://localhost:8080" + ApiPath
17 + url += "/" + strings.Join(req.Path(), "/")
18 +
19 + // TODO: support other encodings once we have multicodec to decode response
20 + // (we shouldn't have to set this here)
21 + encoding := cmds.JSON
22 + req.SetOption(cmds.EncShort, encoding)
23 +
24 + query := "?"
25 + options := req.Options()
26 + for k, v := range options {
27 + query += "&" + k + "=" + v.(string)
28 + }
29 +
30 + httpRes, err := http.Post(url+query, "application/octet-stream", req.Stream())
31 + if err != nil {
32 + return nil, err
33 + }
34 +
35 + res := cmds.NewResponse(req)
36 +
37 + contentType := httpRes.Header["Content-Type"][0]
38 + contentType = strings.Split(contentType, ";")[0]
39 +
40 + if contentType == "application/octet-stream" {
41 + res.SetValue(httpRes.Body)
42 + return res, nil
43 + }
44 +
45 + // TODO: decode based on `encoding`, using multicodec
46 + dec := json.NewDecoder(httpRes.Body)
47 +
48 + if httpRes.StatusCode >= http.StatusBadRequest {
49 + e := cmds.Error{}
50 + err = dec.Decode(&e)
51 + if err != nil {
52 + fmt.Println(err)
53 + return nil, err
54 + }
55 +
56 + res.SetError(e, e.Code)
57 +
58 + } else {
59 + var v interface{}
60 + err = dec.Decode(&v)
61 + if err != nil {
62 + fmt.Println(err)
63 + return nil, err
64 + }
65 +
66 + res.SetValue(v)
67 + }
68 +
69 + return res, nil
70 +}