Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang - DTOs, Entities and Mapping

Tags:

People also ask

Are entities DTOs?

Short answer: Entities may be part of a business domain. Thus, they can implement behavior and be applied to different use cases within the domain. DTOs are used only to transfer data from one process or context to another.

Can we use DTO in repository?

Short answer: No.


I am new to Go having come from a C# background, and I am just plain confused about structure a Go application.

Say I am building a REST API that will sit on top of a database. Also, say that, even after it is complete, this application could need to change somewhat frequently given the vicissitudes of the business, etc.

In C#, with tools like Entity Framework and DTOs, I somewhat alleviate this problem by abstracting the database from the results given by the controllers. If I change the name of a bunch of fields in the database, I might have to change my database access logic. Still, hopefully, the DTOs that I map to my entities using AutoMapper can remain the same, so I don't break frontend functionality that relies on a given DTO structure.

Should I replicate this structure with Go's structs? Something about such an approach seems wrong given that structs are just DTOs, and I will have quite a few DTO structs that are identical to the entity structs. I also have to setup logic to map entities to DTOs. This all just feels very unidiomatic somehow, and many of the examples I see on the web just serialize the database structs.

In short, how do people avoid excessive coupling between their API and the database in Go, and how would they broadly go about separating out the different parts of the application?

If it makes any difference, I am planning to use sqlx to marshal database results into structs which will mean more tags in addition to the JSON ones if I don't separate entities from DTOs.