DTO on Rest API with Golang

Friends, I am creating an API using GoLang. Actually a set of microservices. In this process of creation some doubts arose.

Hey there:

In my API I have a Struct that returns a set of attributes in JSON format. It turns out that depending on the method to invoke, this Struct is returned containing only some of its attributes, not all. In this case, is DTO’S used or is there any other kind of solution in Go to help solve this kind of problem?

Thanks in advance for those who help.

I am from Brazil. My English is more or less

I don’t quite understand what your problem is. Do you want to remove empty (JSON null) elements from the response for those struct fields that are nil?

Do you want to return

   "foo": 1

instead of

  "foo": 1,
  "bar": null

for a struct with bar = nil?

Yes. :slightly_smiling_face:

How can I do it?

Use omitempty:

The “omitempty” option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

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