Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions args/httpie.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ func parseFancyArgs(args []string, postMode PostMode) (opts Opts) {
if postMode == PostModeFORM {
opts = append(opts, "-F", name+"="+value)
} else {
data[name] = value
setJSONData(data, name, value)
}
case jsonArg:
var v interface{}
json.Unmarshal([]byte(value), &v)
data[name] = v
setJSONData(data, name, v)
default:
opts = append(opts, arg)
}
Expand Down Expand Up @@ -121,6 +121,23 @@ func parseArg(arg string) (typ argType, name, value string) {
return
}

// setJSONData stores value under name. Names ending with "[]" follow HTTPie
// array syntax: key[]=a key[]=b becomes {"key":["a","b"]}.
func setJSONData(data map[string]interface{}, name string, value interface{}) {
if strings.HasSuffix(name, "[]") {
key := name[:len(name)-2]
if existing, ok := data[key]; ok {
if arr, ok := existing.([]interface{}); ok {
data[key] = append(arr, value)
return
}
}
data[key] = []interface{}{value}
return
}
data[name] = value
}

func appendURLParam(u, name, value string) string {
sep := "?"
if strings.IndexByte(u, '?') != -1 {
Expand Down
15 changes: 15 additions & 0 deletions args/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,18 @@ func compareStrings(a, b []string) bool {
}
return true
}

func TestParseJSONArrayField(t *testing.T) {
expected := []string{"-X", "POST", "-d", `{"tables":["users"]}`, "example.com"}
parseAndCompare(t, []string{"curlie", "post", "example.com", "tables[]=users"}, expected)
}

func TestParseJSONArrayFieldAppend(t *testing.T) {
expected := []string{"-X", "POST", "-d", `{"tables":["users","admins"]}`, "example.com"}
parseAndCompare(t, []string{"curlie", "post", "example.com", "tables[]=users", "tables[]=admins"}, expected)
}

func TestParseJSONArrayRaw(t *testing.T) {
expected := []string{"-X", "POST", "-d", `{"ids":[1,2]}`, "example.com"}
parseAndCompare(t, []string{"curlie", "post", "example.com", "ids[]:=1", "ids[]:=2"}, expected)
}