Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to parse json without check binding condition? #1916

Open
bakatest-me opened this issue May 26, 2019 · 1 comment
Open

How to parse json without check binding condition? #1916

bakatest-me opened this issue May 26, 2019 · 1 comment

Comments

@bakatest-me
Copy link

  • With issues:

    • Use the search tool before opening a new issue.
    • Please provide source code and commit sha if you found a bug.
    • Review existing issues and provide feedback or react to them.
  • go version: go version go1.11.4 darwin/amd64

  • gin version (or commit ref): 1.4.0

  • operating system: osx

Description

type Data sturct {
 	Name        string   `json:"name,omitempty" bson:"name,omitempty" binding:"required"`
        Number      string             `json:"number,omitempty" bson:"number,omitempty" binding:"required"`
}


//route
var json models.Data
err := c.ShouldBindJSON(&json)
// it's ok for check condition required

How to use same struct without check condition binding?
I use BindJson() have error required when empty field requried.

@fwhezfwhez
Copy link

  1. Copy a same struct without binding,
  2. Not use binding tag, replacing it by another check solution.
  3. Realize a method you want, this is mine usecase for json.
// json bind
func BindWihtoutBindingTag(c *gin.Context, dest interface{}) error {
	if c.ContentType() != "application/json" {
		return errors.New("'BindWithoutBindingTag' only serves for application/json not for " + c.ContentType())
	}
	buf, e := ioutil.ReadAll(c.Request.Body)
	if e != nil {
		return e
	}
	c.Request.Body = ioutil.NopCloser(bytes.NewReader(buf))
	return json.Unmarshal(buf, dest)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants