Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c.BindJSON with optional parameters

Tags:

rest

go

I am using go-gin and trying to implement a PATCH API. 3 fields are editable so I have a struct defined like this

type Person struct {
    Name         string  `form:"name" json:"name" binding:"required"`
    Account      string  `form:"account" json:"account" binding:"required"`
    PrimaryOwner string  `form:"primary_owner" json:"primary_owner" binding:"required"`
}

I am trying to bind json like this:

var json Person
if c.BindJSON(&json) == nil {
        fmt.Println("json matched!!!!!!!")
    }else {
        fmt.Println("json not matched!!!!!!!")
}

Problem is it tries to bind all the parameters. If I give all parameters it gets matched but even if one parameter is missing it goes in else block. In patch API I don't want compulsary binding. If I remove binding:"required" from all fields it always matches, even if I give some key like sdfsdfsdf. How can make binding to all parameters but not all together. The keys in json request body should be verified but all keys should not be required at the same time.

like image 404
codec Avatar asked Oct 03 '16 07:10

codec


1 Answers

Just found that question unanswered.

So you want to bind all parameters and minimal one is required

How can make binding to all parameters but not all together.

You almost answered your question here:

If I remove binding:"required" from all fields it always matches

So I would remove the required and check every value.

var json Person
if err := c.BindJSON(&json); err != nil {
        // error handling here
        // something went wrong
    }
    if json.Name == "" && json.Account == "" && json.PrimaryOwner  == "" {
        // no key is given... 
    }
}
like image 67
apxp Avatar answered Sep 28 '22 03:09

apxp