GO - Request Body parse

I am trying to parse the request body parameters(JSON object) from the POST request

I tried the below option

var user models.User

decoder := json.NewDecoder(request.Body)

decoder.Decode(&user)

fmt.Println(user)

but it returns

{0 }

What am i doing wrong here?

Any help is much appreciated.

1 Like

Check the error from Decode.

1 Like

@calmh, I tried that, the error is nil.

Could you show us the definition of models.User ?

It looks like it contains a single field. What would you expect as user value ?

It could be that models.User has only unexported fields (name not starting with an upercase letter), or the structure definition is missing the json tags.

@Christophe_Meessen below is my user_models.go

package models

// User : User Model
type User struct {
id int
firstName string
lastName string
password string
}

So it has both problems to be used as json output.

  1. The json decoder only consider exported struct field name. A field name is exported when its first lette is in uppercase.

  2. Since the field names in the JSON encoded data are often lowercase, we have to specify the mapping of the json field name and the structure field name. This is done by using tags. Tags are strings enclosed in backticks and placed at the right of the field definition.

Here is how you should define the models.User struct.

type User struct {
    ID int `json:id`
    FirstName string `json:firstName`
    LastName string `json:lastName`
    Password string `json:password`
}

The value after json: is the field name in the json encoded data. If you did gave us an example of JSON encoded data, I would be sure what value should be put there. I assumed that these are the field names in the json encoded data.

1 Like

Note that if you can’t modify models.User because it is from a package you can’t or should not modify, you should than use an intermediate structure with the above definition, decode the JSON data in it, and then copy each field value in the models.User structure.

This intermediate structure is a frequently used pattern.

Thanks @Christophe_Meessen, it solved my problem.:v:

Don’t forget to flag the question as answered by clicking on the checkbox.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.