client.go 4.65 KB
Newer Older
1 2 3
package http

import (
4
	"bytes"
5 6
	"encoding/json"
	"fmt"
7
	"io"
8
	"net/http"
9
	"net/url"
10
	"reflect"
11 12 13
	"strings"

	cmds "github.com/jbenet/go-ipfs/commands"
14
	config "github.com/jbenet/go-ipfs/repo/config"
15 16
)

17
const (
18
	ApiUrlFormat = "http://%s%s/%s?%s"
19 20
	ApiPath      = "/api/v0" // TODO: make configurable
)
21

22 23 24 25 26 27 28 29
// Client is the commands HTTP client interface.
type Client interface {
	Send(req cmds.Request) (cmds.Response, error)
}

type client struct {
	serverAddress string
}
30

31 32 33
func NewClient(address string) Client {
	return &client{address}
}
34

35
func (c *client) Send(req cmds.Request) (cmds.Response, error) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
36 37 38 39 40 41 42 43

	// save user-provided encoding
	previousUserProvidedEncoding, found, err := req.Option(cmds.EncShort).String()
	if err != nil {
		return nil, err
	}

	// override with json to send to server
44
	req.SetOption(cmds.EncShort, cmds.JSON)
45

46 47 48
	// stream channel output
	req.SetOption(cmds.ChanOpt, "true")

49
	query, err := getQuery(req)
50 51 52 53
	if err != nil {
		return nil, err
	}

54
	var fileReader *MultiFileReader
55 56
	var reader io.Reader

57
	if req.Files() != nil {
58
		fileReader = NewMultiFileReader(req.Files(), true)
59 60 61 62 63
		reader = fileReader
	} else {
		// if we have no file data, use an empty Reader
		// (http.NewRequest panics when a nil Reader is used)
		reader = strings.NewReader("")
64 65
	}

66 67 68
	path := strings.Join(req.Path(), "/")
	url := fmt.Sprintf(ApiUrlFormat, c.serverAddress, ApiPath, path, query)

69
	httpReq, err := http.NewRequest("POST", url, reader)
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
	if err != nil {
		return nil, err
	}

	// TODO extract string consts?
	if fileReader != nil {
		httpReq.Header.Set("Content-Type", "multipart/form-data; boundary="+fileReader.Boundary())
		httpReq.Header.Set("Content-Disposition", "form-data: name=\"files\"")
	} else {
		httpReq.Header.Set("Content-Type", "application/octet-stream")
	}
	version := config.CurrentVersionNumber
	httpReq.Header.Set("User-Agent", fmt.Sprintf("/go-ipfs/%s/", version))

	httpRes, err := http.DefaultClient.Do(httpReq)
85 86 87 88
	if err != nil {
		return nil, err
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
89
	// using the overridden JSON encoding in request
90 91 92 93 94
	res, err := getResponse(httpRes, req)
	if err != nil {
		return nil, err
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
95 96 97 98 99
	if found && len(previousUserProvidedEncoding) > 0 {
		// reset to user provided encoding after sending request
		// NB: if user has provided an encoding but it is the empty string,
		// still leave it as JSON.
		req.SetOption(cmds.EncShort, previousUserProvidedEncoding)
100 101 102 103 104
	}

	return res, nil
}

105
func getQuery(req cmds.Request) (string, error) {
106
	query := url.Values{}
107
	for k, v := range req.Options() {
108
		str := fmt.Sprintf("%v", v)
109
		query.Set(k, str)
110
	}
111 112

	args := req.Arguments()
113 114
	argDefs := req.Command().Arguments

115 116 117 118 119 120 121 122
	argDefIndex := 0

	for _, arg := range args {
		argDef := argDefs[argDefIndex]
		// skip ArgFiles
		for argDef.Type == cmds.ArgFile {
			argDefIndex++
			argDef = argDefs[argDefIndex]
123 124
		}

125 126 127 128
		query.Add("arg", arg)

		if len(argDefs) > argDefIndex+1 {
			argDefIndex++
129
		}
130
	}
131

132
	return query.Encode(), nil
133
}
134

135 136 137
// getResponse decodes a http.Response to create a cmds.Response
func getResponse(httpRes *http.Response, req cmds.Request) (cmds.Response, error) {
	var err error
138 139 140 141 142
	res := cmds.NewResponse(req)

	contentType := httpRes.Header["Content-Type"][0]
	contentType = strings.Split(contentType, ";")[0]

143
	if len(httpRes.Header.Get(streamHeader)) > 0 {
144
		// if output is a stream, we can just use the body reader
145
		res.SetOutput(httpRes.Body)
146
		return res, nil
147 148 149 150 151 152

	} else if len(httpRes.Header.Get(channelHeader)) > 0 {
		// if output is coming from a channel, decode each chunk
		outChan := make(chan interface{})
		go func() {
			dec := json.NewDecoder(httpRes.Body)
153
			outputType := reflect.TypeOf(req.Command().Type)
154 155

			for {
156 157
				v := reflect.New(outputType).Interface()
				err := dec.Decode(v)
158 159 160 161 162 163
				if err != nil && err != io.EOF {
					fmt.Println(err.Error())
					return
				}
				if err == io.EOF {
					close(outChan)
164 165 166 167 168 169 170 171
					return
				}
				outChan <- v
			}
		}()

		res.SetOutput(outChan)
		return res, nil
172 173 174 175 176 177
	}

	dec := json.NewDecoder(httpRes.Body)

	if httpRes.StatusCode >= http.StatusBadRequest {
		e := cmds.Error{}
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

		if httpRes.StatusCode == http.StatusNotFound {
			// handle 404s
			e.Message = "Command not found."
			e.Code = cmds.ErrClient

		} else if contentType == "text/plain" {
			// handle non-marshalled errors
			buf := bytes.NewBuffer(nil)
			io.Copy(buf, httpRes.Body)
			e.Message = string(buf.Bytes())
			e.Code = cmds.ErrNormal

		} else {
			// handle marshalled errors
			err = dec.Decode(&e)
			if err != nil {
				return nil, err
			}
197 198 199 200 201
		}

		res.SetError(e, e.Code)

	} else {
202 203 204
		outputType := reflect.TypeOf(req.Command().Type)
		v := reflect.New(outputType).Interface()
		err = dec.Decode(v)
205
		if err != nil && err != io.EOF {
206 207 208
			return nil, err
		}

209
		res.SetOutput(v)
210 211
	}

212 213
	return res, nil
}