client.go 3.5 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 11 12
	"strings"

	cmds "github.com/jbenet/go-ipfs/commands"
13
	u "github.com/jbenet/go-ipfs/util"
14 15
)

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

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

type client struct {
	serverAddress string
}
29

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

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

	// 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
43
	req.SetOption(cmds.EncShort, cmds.JSON)
44

45
	query, inputStream, err := getQuery(req)
46 47 48 49 50 51 52
	if err != nil {
		return nil, err
	}

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

Brian Tiger Chow's avatar
Brian Tiger Chow committed
53
	// TODO extract string const?
54
	httpRes, err := http.Post(url, "application/octet-stream", inputStream)
55 56 57 58
	if err != nil {
		return nil, err
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
59
	// using the overridden JSON encoding in request
60 61 62 63 64
	res, err := getResponse(httpRes, req)
	if err != nil {
		return nil, err
	}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
65 66 67 68 69
	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)
70 71 72 73 74 75
	}

	return res, nil
}

func getQuery(req cmds.Request) (string, io.Reader, error) {
76
	// TODO: handle multiple files with multipart
77
	var inputStream io.Reader
78

79
	query := url.Values{}
80
	for k, v := range req.Options() {
81
		str := fmt.Sprintf("%v", v)
82
		query.Set(k, str)
83
	}
84 85

	args := req.Arguments()
86 87 88
	argDefs := req.Command().Arguments
	var argDef cmds.Argument

89
	for i, arg := range args {
90 91 92 93 94
		if i < len(argDefs) {
			argDef = argDefs[i]
		}

		if argDef.Type == cmds.ArgString {
95 96
			str, ok := arg.(string)
			if !ok {
97
				return "", nil, u.ErrCast()
98 99
			}
			query.Add("arg", str)
100 101 102

		} else {
			// TODO: multipart
103
			if inputStream != nil {
104
				return "", nil, fmt.Errorf("Currently, only one file stream is possible per request")
105
			}
106 107 108
			var ok bool
			inputStream, ok = arg.(io.Reader)
			if !ok {
109
				return "", nil, u.ErrCast()
110
			}
111
		}
112
	}
113

114
	return query.Encode(), inputStream, nil
115
}
116

117 118 119
// getResponse decodes a http.Response to create a cmds.Response
func getResponse(httpRes *http.Response, req cmds.Request) (cmds.Response, error) {
	var err error
120 121 122 123 124
	res := cmds.NewResponse(req)

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

125
	if len(httpRes.Header.Get(streamHeader)) > 0 {
126
		res.SetOutput(httpRes.Body)
127 128 129 130 131 132 133
		return res, nil
	}

	dec := json.NewDecoder(httpRes.Body)

	if httpRes.StatusCode >= http.StatusBadRequest {
		e := cmds.Error{}
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152

		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
			}
153 154 155 156 157
		}

		res.SetError(e, e.Code)

	} else {
158
		v := req.Command().Type
159
		err = dec.Decode(&v)
160
		if err != nil && err != io.EOF {
161 162 163
			return nil, err
		}

164
		res.SetOutput(v)
165 166
	}

167 168
	return res, nil
}