I have a api with one attribute of body as
type Reg struct{
Env []string json:"env"
}
while calling the api I need to pass value of "env" as optional parameter.
i.e.
in this format env: []
, and not as env: ""
Can anyone help pls.
I have tried using len(env)==0 but it take both "" and [] as empty. I have also tried using reflect.ValueOf(Reg.Env).Kind() == reflect.Slice to differentiate between "" and [] but it takes both the values as slice only.
CodePudding user response:
If you check the error of json.Unmarshal
, for example, you will know if the user passed invalid input.
var r struct { Env []string `json:"env"` }
if err := json.Unmarshal([]byte(`{"env": ""}`), &r); err != nil {
fmt.Println(err)
}
Produces this error message:
json: cannot unmarshal string into Go struct field .env of type []string
https://go.dev/play/p/LozhJ14C7zj
The same happens when you use a decoder. I.e. from a http requests body.
var r struct { Env []string `json:"env"` }
dec := json.NewDecoder(strings.NewReader(`{"env": ""}`))
if err := dec.Decode(&r); err != nil { fmt.Println(err) }
https://go.dev/play/p/_XpY3jquxVx
CodePudding user response:
There are multiple options depending on what do you need to send:
Case A:
Reg{}
will be json-serialized to {"env": null}
Case B:
Reg{Env: []string{} }
will be json-serialized to {"env": []}
Case C:
If ,omitempty
is added to the struct tag like this:
type Reg struct {
Env []string `json:"env,omitempty"`
}
then Reg{}
will be json-serialized to {}
See code example here: https://go.dev/play/p/lKI91VCoI0V