parse.go 2.11 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
			for j := 0; len(stringArgs) > 0 && arg.Variadic || j == 0; j++ {
				args = append(args, stringArgs[0])
50 51 52 53 54
				stringArgs = stringArgs[1:]
			}

		} else {
			// TODO: create multipart streams for file args
55
			args = append(args, r.Body)
56 57
		}
	}
58

59 60 61 62 63 64 65 66
	req := cmds.NewRequest(path, opts, args, cmd)

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

	return req, nil
67 68
}

69
func parseOptions(r *http.Request) (map[string]interface{}, []string) {
70
	opts := make(map[string]interface{})
71
	var args []string
72 73 74

	query := r.URL.Query()
	for k, v := range query {
Matt Bell's avatar
Matt Bell committed
75
		if k == "arg" {
76
			args = v
Matt Bell's avatar
Matt Bell committed
77 78 79
		} else {
			opts[k] = v[0]
		}
80 81 82 83 84 85 86 87 88
	}

	// 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
89
	return opts, args
90
}