Need to pass empty slice in [] this format and not as ""

Issue

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.

Solution

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

Answered By – The Fool

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.