Member-only story
Converting Request Model to Database Model Using Copier in Golang
Introduction
In this blog post, we will delve into a common task in Golang: converting a request model to a database model. The practice of translating between different data models is a crucial aspect of backend development. We’ll be focusing on the use of the ‘copier’ package in Go, which is a powerful tool that simplifies the process of copying between structures with similar fields.
The Problem
Often, we have a request model where all fields are optional. This flexibility allows the UI to develop various forms.
For example. Let’s assume we are building a User Management System and the UI has different forms for creating and updating user information. For instance, there is a form for user registration, another form for updating profile, and another for resetting password.
Request Model
type UserRequest struct {
Name *string `json:"name,omitempty"`
Email *string `json:"email,omitempty"`
Password *string `json:"password,omitempty"`
}
In this request model, all fields are pointers and hence optional.