Skip to content

Add BindAll and ShouldBindAll methods to bind header, uri, query params, and body in one call #4510

@takanuva15

Description

@takanuva15

Feature Description

Problem

There have been multiple issues raised and even a PR requesting a feature to allow Gin to bind headers, request path params, query params, and body in a single call:

Most of these show the standard workaround of a split-struct solution where 2 separate structs are used to bind uri and body separately in separate calls:

type UserGetRequest struct {
	Id models.Id `uri:"id" binding:"required"`
}

type UserUpdateRequest struct {
	Nickname string `json:"nickname" `
}

func UserUpdate(context *gin.Context)  {
	var (
                locator  = new(UserGetRequest)
		request = new(UserUpdateRequest)
	)

	if err = context.BindUri(&params); err != nil {
		return
	}

	if err = context.BindJSON(&request); err != nil {
		return
	}

	var action = upms.UserUpdateAction{
		Nickname: request.Nickname,
	}

	if user, err = upms.UserUpdate(domain, locator.Id, action); err == nil {
		.....
	}

	return
}

This is required to avoid violating the binding:required tags on all fields, since ShouldBindUri checks all binding tags even on non-uri fields. But this is also frustrating to many developers as highlighted by the large number of issue requests to add a method to bind all request parts at once.

Solution

To resolve this, we should have BindAll and ShouldBindAll methods that can bind these various request parts to a single struct based on the appropriate tags (eg uri vs form vs header), AND only apply binding validation after all fields and request parts have been processed and bound.

I will raise a PR with full unit tests like I did in my previous PR

Metadata

Metadata

Assignees

No one assigned

    Labels

    type/proposalGot an idea for a feature that Gin doesn't have currently? Submit your idea here!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions