Skip to content
This repository has been archived by the owner on Aug 1, 2023. It is now read-only.

Alter BuildQuery to handle map #630

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
20 changes: 20 additions & 0 deletions params.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gophercloud

import (
"encoding/json"
"fmt"
"net/url"
"reflect"
Expand Down Expand Up @@ -155,6 +156,17 @@ func BuildQueryString(opts interface{}) (*url.URL, error) {
params.Add(tags[0], v.Index(i).String())
}
}
case reflect.Map:
vi := v.Interface()
mp, ok := vi.(map[string]string)
if !ok {
return nil, fmt.Errorf("Query opt [%v] is not type map[string]string, not supported.", v)
}
s, err := buildMapParam(mp)
if err != nil {
return nil, err
}
params.Add(tags[0], s)
}
} else {
// Otherwise, the field is not set.
Expand All @@ -172,6 +184,14 @@ func BuildQueryString(opts interface{}) (*url.URL, error) {
return nil, fmt.Errorf("Options type is not a struct.")
}

func buildMapParam(v map[string]string) (string, error) {
s, err := json.Marshal(v)
if err != nil {
return "", err
}
return string(s), nil
}

/*
BuildHeaders is an internal function to be used by request methods in
individual resource packages.
Expand Down
29 changes: 16 additions & 13 deletions params_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,34 +36,37 @@ func TestMaybeInt(t *testing.T) {
func TestBuildQueryString(t *testing.T) {
type testVar string
opts := struct {
J int `q:"j"`
R string `q:"r,required"`
C bool `q:"c"`
S []string `q:"s"`
TS []testVar `q:"ts"`
TI []int `q:"ti"`
J int `q:"j"`
R string `q:"r,required"`
C bool `q:"c"`
S []string `q:"s"`
TS []testVar `q:"ts"`
TI []int `q:"ti"`
MP map[string]string `q:"mp"`
}{
J: 2,
R: "red",
C: true,
S: []string{"one", "two", "three"},
TS: []testVar{"a", "b"},
TI: []int{1, 2},
MP: map[string]string{"k1": "v1", "k2": "v2"},
}
expected := &url.URL{RawQuery: "c=true&j=2&r=red&s=one&s=two&s=three&ti=1&ti=2&ts=a&ts=b"}
expected := &url.URL{RawQuery: "c=true&j=2&mp=%7B%22k1%22%3A%22v1%22%2C%22k2%22%3A%22v2%22%7D&r=red&s=one&s=two&s=three&ti=1&ti=2&ts=a&ts=b"}
actual, err := BuildQueryString(&opts)
if err != nil {
t.Errorf("Error building query string: %v", err)
}
th.CheckDeepEquals(t, expected, actual)

opts = struct {
J int `q:"j"`
R string `q:"r,required"`
C bool `q:"c"`
S []string `q:"s"`
TS []testVar `q:"ts"`
TI []int `q:"ti"`
J int `q:"j"`
R string `q:"r,required"`
C bool `q:"c"`
S []string `q:"s"`
TS []testVar `q:"ts"`
TI []int `q:"ti"`
MP map[string]string `q:"mp"`
}{
J: 2,
C: true,
Expand Down