-
Notifications
You must be signed in to change notification settings - Fork 8.1k
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 binding param and json #2535
Comments
Bind twice. g.POST("/user/:id", func(c *gin.Context) {
var u UserRequest
if err := c.ShouldBindUri(&u); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := c.ShouldBindJSON(&u); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
fmt.Printf("id: %d nickname: %s mobile: %s email: %s\n", u.Id, u.Nickname, u.Mobile, u.Email)
c.JSON(http.StatusNoContent, nil)
}) This is the related issue. Please tell me if there is another good way! |
I also want to know if there is another way |
Can't you do something like
|
It seems that it is not possible to bind successfully by calling the API once. |
Only work with non-required fields. Is there anyway with required fields?
|
As mentioned above, the workaround (bind twice) doesn't work with required fields. |
+1 on this. Any updates or workarounds for required fields? |
+1 |
6 similar comments
+1 |
+1 |
+1 |
+1 |
+1 |
+1 |
ok here is an example : // here ,we can use this struct in get method again.
type UserGetRequest struct {
Id models.Id `uri:"id" binding:"required"`
}
type UserUpdateRequest struct {
Nickname string `json:"nickname" `
}
func UserGet(context *gin.Context, domain *domains.Context) {
var (
locator = new(UserGetRequest)
)
if err = context.BindUri(locator); err != nil {
return
}
if user, err = upms.UserGet(domain, locator.Id); err == nil {
...
}
return
}
func UserUpdate(context *gin.Context) {
var (
locator = new(UserGetRequest)
request = new(UserUpdateRequest)
)
if err = context.BindUri(¶ms); 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
} |
Is it a good idea to support something like |
This worked for me:
|
How to reproduce
The text was updated successfully, but these errors were encountered: