@cryptotaxi247 / kubo / commits / c89826c1e

cmd/ipfs: Added HTTP RPC client to entry point

Matt Bell committed Oct 23, 2014 at 17:14 UTC c89826c1ef4f610df0cd645525761fc7e4337e77
1 file changed +69 -2
cmd/ipfs/ipfs.go
+69 -2
@@ -1,10 +1,13 @@
1 package main
2
3 import (
4 + "encoding/json"
5 "fmt"
6 "io"
7 + "net/http"
8 "os"
9 "runtime/pprof"
10 + "strings"
11
12 cmds "github.com/jbenet/go-ipfs/commands"
13 "github.com/jbenet/go-ipfs/commands/cli"
@@ -24,13 +27,19 @@ func main() {
27 os.Exit(1)
28 }
29
30 + // TODO: call command locally if option tells us to, or if command is CLI-only (e.g. ipfs init)
31 +
32 cmd, err := commands.Root.Get(req.Path())
33 if err != nil {
34 fmt.Println(err)
35 os.Exit(1)
36 }
37
33 - // TODO: send request to daemon via HTTP API
38 + res, err := sendRequest(req)
39 + if err != nil {
40 + fmt.Println(err)
41 + os.Exit(1)
42 + }
43
44 if debug, ok := req.Option("debug"); ok && debug.(bool) {
45 u.Debug = true
@@ -48,7 +57,7 @@ func main() {
57 }
58 }
59
51 - res := commands.Root.Call(req)
60 + //res := commands.Root.Call(req)
61
62 if res.Error() != nil {
63 fmt.Println(res.Error().Error())
@@ -66,3 +75,61 @@ func main() {
75 fmt.Println(err.Error())
76 }
77 }
78 +
79 +func sendRequest(req cmds.Request) (cmds.Response, error) {
80 + // TODO: load RPC host from config
81 + url := "http://localhost:8080" + API_PATH
82 + url += "/" + strings.Join(req.Path(), "/")
83 +
84 + // TODO: support other encodings once we have multicodec to decode response
85 + // (we shouldn't have to set this here)
86 + encoding := cmds.JSON
87 + req.SetOption(cmds.EncShort, encoding)
88 +
89 + query := "?"
90 + options := req.Options()
91 + for k, v := range options {
92 + query += "&" + k + "=" + v.(string)
93 + }
94 +
95 + httpRes, err := http.Post(url+query, "application/octet-stream", req.Stream())
96 + if err != nil {
97 + return nil, err
98 + }
99 +
100 + res := cmds.NewResponse(req)
101 +
102 + contentType := httpRes.Header["Content-Type"][0]
103 + contentType = strings.Split(contentType, ";")[0]
104 +
105 + if contentType == "application/octet-stream" {
106 + res.SetValue(httpRes.Body)
107 + return res, nil
108 + }
109 +
110 + // TODO: decode based on `encoding`, using multicodec
111 + dec := json.NewDecoder(httpRes.Body)
112 +
113 + if httpRes.StatusCode >= http.StatusBadRequest {
114 + e := cmds.Error{}
115 + err = dec.Decode(&e)
116 + if err != nil {
117 + fmt.Println(err)
118 + return nil, err
119 + }
120 +
121 + res.SetError(e, e.Code)
122 +
123 + } else {
124 + var v interface{}
125 + err = dec.Decode(&v)
126 + if err != nil {
127 + fmt.Println(err)
128 + return nil, err
129 + }
130 +
131 + res.SetValue(v)
132 + }
133 +
134 + return res, nil
135 +}