parse.go 1.98 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package http

import (
	"net/http"
	"strings"

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

// Parse parses the data in a http.Request and returns a command Request object
11
func Parse(r *http.Request, root *cmds.Command) (cmds.Request, error) {
12
	path := strings.Split(r.URL.Path, "/")[3:]
13
	stringArgs := make([]string, 0)
14

15
	cmd, err := root.Get(path[:len(path)-1])
16
	if err != nil {
Matt Bell's avatar
Matt Bell committed
17
		// 404 if there is no command at that path
18
		return nil, ErrNotFound
Matt Bell's avatar
Matt Bell committed
19

20
	} else if sub := cmd.Subcommand(path[len(path)-1]); sub == nil {
21 22 23 24
		if len(path) <= 1 {
			return nil, ErrNotFound
		}

Matt Bell's avatar
Matt Bell committed
25 26
		// 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)
27
		stringArgs = append(stringArgs, path[len(path)-1])
Matt Bell's avatar
Matt Bell committed
28
		path = path[:len(path)-1]
29 30 31

	} else {
		cmd = sub
32 33
	}

34 35 36 37 38
	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)
39 40 41
	args := make([]interface{}, 0)

	for _, arg := range cmd.Arguments {
42
		if arg.Type == cmds.ArgString {
43 44
			for j := 0; len(stringArgs) > 0 && arg.Variadic || j == 0; j++ {
				args = append(args, stringArgs[0])
45 46 47 48 49
				stringArgs = stringArgs[1:]
			}

		} else {
			// TODO: create multipart streams for file args
50
			args = append(args, r.Body)
51 52
		}
	}
53

54 55 56 57 58 59 60 61
	req := cmds.NewRequest(path, opts, args, cmd)

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

	return req, nil
62 63
}

64
func parseOptions(r *http.Request) (map[string]interface{}, []string) {
65
	opts := make(map[string]interface{})
66
	var args []string
67 68 69

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

	// 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
84
	return opts, args
85
}