Allow bind with a map[string]string (#2484)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Alessandro (Ale) Segala · committed by GitHub · parent 16cd8cd · Browse files · 3 files·+143 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: thinkerou <thinkerou@gmail.com>
Diff stats
3 files+143 added−0 removed
- other:+143 added−0 removed
Provenance
- Commit
65ed60e- Tree
76ef276- Author
Alessandro (Ale) Segala <43508+ItalyPaleAle@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
16cd8cd
3 files changed+143 added−0 removed
modified:binding/binding_test.go+93 added
11 unmodified lines12 "io/ioutil"13 "mime/multipart"14 "net/http"15 "os"16+ "reflect"17 "strconv"18 "strings"19 "testing"20 "time"179 unmodified lines200 "/", "/",201 `{"foo": "bar"}`, `{"foo": "bar", "what": "this"}`)202 }203 204+func TestBindingJSONStringMap(t *testing.T) {205+ testBodyBindingStringMap(t, JSON,206+ "/", "/",207+ `{"foo": "bar", "hello": "world"}`, `{"num": 2}`)208+}209+210 func TestBindingForm(t *testing.T) {211 testFormBinding(t, "POST",212 "/", "/",213 "foo=bar&bar=foo", "bar2=foo")128 unmodified lines342 "/?name=thinkerou", "/?name1=ou",343 "", "", "StructPointer")344 }345 346+func TestBindingFormStringMap(t *testing.T) {347+ testBodyBindingStringMap(t, Form,348+ "/", "",349+ `foo=bar&hello=world`, "")350+ // Should pick the last value351+ testBodyBindingStringMap(t, Form,352+ "/", "",353+ `foo=something&foo=bar&hello=world`, "")354+}355+356+func TestBindingFormStringSliceMap(t *testing.T) {357+ obj := make(map[string][]string)358+ req := requestWithBody("POST", "/", "foo=something&foo=bar&hello=world")359+ req.Header.Add("Content-Type", MIMEPOSTForm)360+ err := Form.Bind(req, &obj)361+ assert.NoError(t, err)362+ assert.NotNil(t, obj)363+ assert.Len(t, obj, 2)364+ target := map[string][]string{365+ "foo": {"something", "bar"},366+ "hello": {"world"},367+ }368+ assert.True(t, reflect.DeepEqual(obj, target))369+370+ objInvalid := make(map[string][]int)371+ req = requestWithBody("POST", "/", "foo=something&foo=bar&hello=world")372+ req.Header.Add("Content-Type", MIMEPOSTForm)373+ err = Form.Bind(req, &objInvalid)374+ assert.Error(t, err)375+}376+377 func TestBindingQuery(t *testing.T) {378 testQueryBinding(t, "POST",379 "/?foo=bar&bar=foo", "/",380 "foo=unused", "bar2=foo")22 unmodified lines403 "/?bool_foo=fasl", "/?bar2=foo",404 "bool_foo=unused", "")405 }406 407+func TestBindingQueryStringMap(t *testing.T) {408+ b := Query409+410+ obj := make(map[string]string)411+ req := requestWithBody("GET", "/?foo=bar&hello=world", "")412+ err := b.Bind(req, &obj)413+ assert.NoError(t, err)414+ assert.NotNil(t, obj)415+ assert.Len(t, obj, 2)416+ assert.Equal(t, "bar", obj["foo"])417+ assert.Equal(t, "world", obj["hello"])418+419+ obj = make(map[string]string)420+ req = requestWithBody("GET", "/?foo=bar&foo=2&hello=world", "") // should pick last421+ err = b.Bind(req, &obj)422+ assert.NoError(t, err)423+ assert.NotNil(t, obj)424+ assert.Len(t, obj, 2)425+ assert.Equal(t, "2", obj["foo"])426+ assert.Equal(t, "world", obj["hello"])427+}428+429 func TestBindingXML(t *testing.T) {430 testBodyBinding(t,431 XML, "xml",432 "/", "/",13 unmodified lines446 "/", "/",447 `foo: bar`, `bar: foo`)448 }449 450+func TestBindingYAMLStringMap(t *testing.T) {451+ // YAML is a superset of JSON, so the test below is JSON (to avoid newlines)452+ testBodyBindingStringMap(t, YAML,453+ "/", "/",454+ `{"foo": "bar", "hello": "world"}`, `{"nested": {"foo": "bar"}}`)455+}456+457 func TestBindingYAMLFail(t *testing.T) {458 testBodyBindingFail(t,459 YAML, "yaml",460 "/", "/",719 unmodified lines1180 err = JSON.Bind(req, &obj)1181 assert.Error(t, err)1182 }1183 1184+func testBodyBindingStringMap(t *testing.T, b Binding, path, badPath, body, badBody string) {1185+ obj := make(map[string]string)1186+ req := requestWithBody("POST", path, body)1187+ if b.Name() == "form" {1188+ req.Header.Add("Content-Type", MIMEPOSTForm)1189+ }1190+ err := b.Bind(req, &obj)1191+ assert.NoError(t, err)1192+ assert.NotNil(t, obj)1193+ assert.Len(t, obj, 2)1194+ assert.Equal(t, "bar", obj["foo"])1195+ assert.Equal(t, "world", obj["hello"])1196+1197+ if badPath != "" && badBody != "" {1198+ obj = make(map[string]string)1199+ req = requestWithBody("POST", badPath, badBody)1200+ err = b.Bind(req, &obj)1201+ assert.Error(t, err)1202+ }1203+1204+ objInt := make(map[string]int)1205+ req = requestWithBody("POST", path, body)1206+ err = b.Bind(req, &objInt)1207+ assert.Error(t, err)1208+}1209+1210 func testBodyBindingUseNumber(t *testing.T, b Binding, name, path, badPath, body, badBody string) {1211 assert.Equal(t, name, b.Name())1212 1213 obj := FooStructUseNumber{}112 unmodified linesmodified:binding/form_mapping.go+41 added
27 unmodified lines28 29 var emptyField = reflect.StructField{}30 31 func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error {32+ // Check if ptr is a map33+ ptrVal := reflect.ValueOf(ptr)34+ var pointed interface{}35+ if ptrVal.Kind() == reflect.Ptr {36+ ptrVal = ptrVal.Elem()37+ pointed = ptrVal.Interface()38+ }39+ if ptrVal.Kind() == reflect.Map &&40+ ptrVal.Type().Key().Kind() == reflect.String {41+ if pointed != nil {42+ ptr = pointed43+ }44+ return setFormMap(ptr, form)45+ }46+47 return mappingByPtr(ptr, formSource(form), tag)48 }49 50 // setter tries to set value on a walking by fields of a struct312 unmodified lines363 return str, ""364 }365 return str[:idx], str[idx+len(sep):]366 }367+368+func setFormMap(ptr interface{}, form map[string][]string) error {369+ el := reflect.TypeOf(ptr).Elem()370+371+ if el.Kind() == reflect.Slice {372+ ptrMap, ok := ptr.(map[string][]string)373+ if !ok {374+ return errors.New("cannot convert to map slices of strings")375+ }376+ for k, v := range form {377+ ptrMap[k] = v378+ }379+380+ return nil381+ }382+383+ ptrMap, ok := ptr.(map[string]string)384+ if !ok {385+ return errors.New("cannot convert to map of strings")386+ }387+ for k, v := range form {388+ ptrMap[k] = v[len(v)-1] // pick last389+ }390+391+ return nil392+}modified:binding/json_test.go+9 added
17 unmodified lines18 err := jsonBinding{}.BindBody([]byte(`{"foo": "FOO"}`), &s)19 require.NoError(t, err)20 assert.Equal(t, "FOO", s.Foo)21 }22+23+func TestJSONBindingBindBodyMap(t *testing.T) {24+ s := make(map[string]string)25+ err := jsonBinding{}.BindBody([]byte(`{"foo": "FOO","hello":"world"}`), &s)26+ require.NoError(t, err)27+ assert.Len(t, s, 2)28+ assert.Equal(t, "FOO", s["foo"])29+ assert.Equal(t, "world", s["hello"])30+}