Home > OS >  Do I need to add nil check after decoding a pointer value with the json package?
Do I need to add nil check after decoding a pointer value with the json package?

Time:10-19

I have been writing in Go for a long time and recently while rewriting the code I came across a strange thing. I did a couple of tests and if request == nil check never worked. Previously, I was always afraid of getting a nil pointer exception, and so I inserted checks everywhere. But in this case, the json decode error handler seems to cover all cases.

    var (
        request *models.Owner
        err     error
    )

    err = json.NewDecoder(r.Body).Decode(&request)
    if err != nil {
        render.Render(w, r, response.ErrInvalidRequest(err))
        return
    }

    if request == nil {
        render.Render(w, r, response.ErrInvalidRequest("request is nil"))
        return
    }

if request == nil is it possible to catch this? Perhaps this check is unnecessary, and if I remove this check in my project, the code will become cleaner.

CodePudding user response:

It is possible that nil error will be returned and request will still be nil, but only if the input JSON is the JSON null value.

For example:

type Owners struct {
    Name string
}

var request *Owners

if err := json.Unmarshal([]byte("null"), &request); err != nil {
    panic(err)
}

fmt.Println(request == nil)
fmt.Println(request)

This will output (try it on the Go Playground):

true
<nil>

This is documented at json.Unmarshal():

To unmarshal JSON into a pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates a new value for it to point to.

  • Related