Skip to content

DefaultBinder.Bind() binds path/query params to struct fields without TAG #1729

Closed
@aldas

Description

@aldas

This is continuation of #1681 discussions to 'fix' problems with Bind

  1. change struct binding work only when tag exists (do not use field name as backup) + update docs

Originally posted by @aldas in #1681 (comment)

So I started to work with do not bind to field without tag requirement and I'll document some findings here that will be changed with this requirement.

Example with current behaviour (without modifications)

func TestToMultipleFields(t *testing.T) {
	e := New()
	req := httptest.NewRequest(http.MethodGet, "/?id=1&ID=2", nil)
	rec := httptest.NewRecorder()
	c := e.NewContext(req, rec)

	type Root struct {
		ID int64 `query:"id"`
		Child2 struct{
			ID int64
		}
		Child1 struct{
			ID int64 `query:"id"`
		}
	}

	u := new(Root)
	err := c.Bind(u)
	if assert.NoError(t, err) {
		assert.Equal(t, int64(1), u.ID) // perfectly reasonable
		assert.Equal(t, int64(1), u.Child1.ID) // untagged struct containing tagged field gets filled (by tag)
		assert.Equal(t, int64(2), u.Child2.ID) // untagged struct containing untagged field gets filled (by matching name)
	}
}
  1. One query param can be binded to multiple fields.
    • fine so far - will be possible in future
  2. If bind destination is struct contaning struct fields then matching query params will be bind for each struct in hierarchy. Those inner structs do not need tags atm.
    • after this change u.Child1.ID will be bind but u.Child2.ID will not as later does not have a tag for id

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions