parse.go 2.19 KB
Newer Older
1 2 3
package http

import (
4
	"errors"
5 6 7 8 9 10 11
	"net/http"
	"strings"

	cmds "github.com/jbenet/go-ipfs/commands"
)

// Parse parses the data in a http.Request and returns a command Request object
12
func Parse(r *http.Request, root *cmds.Command) (cmds.Request, error) {
13 14 15 16 17
	if !strings.HasPrefix(r.URL.Path, ApiPath) {
		return nil, errors.New("Unexpected path prefix")
	}
	path := strings.Split(strings.TrimPrefix(r.URL.Path, ApiPath+"/"), "/")

18
	stringArgs := make([]string, 0)
19

20
	cmd, err := root.Get(path[:len(path)-1])
21
	if err != nil {
Matt Bell's avatar
Matt Bell committed
22
		// 404 if there is no command at that path
23
		return nil, ErrNotFound
Matt Bell's avatar
Matt Bell committed
24

25
	} else if sub := cmd.Subcommand(path[len(path)-1]); sub == nil {
26 27 28 29
		if len(path) <= 1 {
			return nil, ErrNotFound
		}

Matt Bell's avatar
Matt Bell committed
30 31
		// if the last string in the path isn't a subcommand, use it as an argument
		// e.g. /objects/Qabc12345 (we are passing "Qabc12345" to the "objects" command)
32
		stringArgs = append(stringArgs, path[len(path)-1])
Matt Bell's avatar
Matt Bell committed
33
		path = path[:len(path)-1]
34 35 36

	} else {
		cmd = sub
37 38
	}

39 40 41 42 43
	opts, stringArgs2 := parseOptions(r)
	stringArgs = append(stringArgs, stringArgs2...)

	// Note that the argument handling here is dumb, it does not do any error-checking.
	// (Arguments are further processed when the request is passed to the command to run)
44 45 46
	args := make([]interface{}, 0)

	for _, arg := range cmd.Arguments {
47
		if arg.Type == cmds.ArgString {
48 49 50 51 52 53
			if arg.Variadic {
				for _, s := range stringArgs {
					args = append(args, s)
				}

			} else if len(stringArgs) > 0 {
54
				args = append(args, stringArgs[0])
55
				stringArgs = stringArgs[1:]
56 57 58

			} else {
				break
59 60 61 62
			}

		} else {
			// TODO: create multipart streams for file args
63
			args = append(args, r.Body)
64 65
		}
	}
66

67 68 69 70 71 72 73 74
	req := cmds.NewRequest(path, opts, args, cmd)

	err = cmd.CheckArguments(req)
	if err != nil {
		return nil, err
	}

	return req, nil
75 76
}

77
func parseOptions(r *http.Request) (map[string]interface{}, []string) {
78
	opts := make(map[string]interface{})
79
	var args []string
80 81 82

	query := r.URL.Query()
	for k, v := range query {
Matt Bell's avatar
Matt Bell committed
83
		if k == "arg" {
84
			args = v
Matt Bell's avatar
Matt Bell committed
85 86 87
		} else {
			opts[k] = v[0]
		}
88 89 90 91 92 93 94 95 96
	}

	// default to setting encoding to JSON
	_, short := opts[cmds.EncShort]
	_, long := opts[cmds.EncLong]
	if !short && !long {
		opts[cmds.EncShort] = cmds.JSON
	}

Matt Bell's avatar
Matt Bell committed
97
	return opts, args
98
}