parse.go 1.47 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
	args := make([]interface{}, 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 27 28
		// 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)
		args = append(args, path[len(path)-1])
		path = path[:len(path)-1]
29 30 31

	} else {
		cmd = sub
32 33
	}

Matt Bell's avatar
Matt Bell committed
34 35
	opts, args2 := parseOptions(r)
	args = append(args, args2...)
36

37
	return cmds.NewRequest(path, opts, args, cmd), nil
38 39
}

40
func parseOptions(r *http.Request) (map[string]interface{}, []interface{}) {
41
	opts := make(map[string]interface{})
42
	args := make([]interface{}, 0)
43 44 45

	query := r.URL.Query()
	for k, v := range query {
Matt Bell's avatar
Matt Bell committed
46
		if k == "arg" {
47 48 49
			for _, s := range v {
				args = append(args, interface{}(s))
			}
Matt Bell's avatar
Matt Bell committed
50 51 52
		} else {
			opts[k] = v[0]
		}
53 54
	}

55 56
	// TODO: create multipart streams for file args

57 58 59 60 61 62 63
	// 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
64
	return opts, args
65
}