Forms
Forms are data contracts that are used to send responses to clients and receive/ bind user input.
Each model can have many forms to enable sending specific values with different endpoints. An example scenario would be having an admin with full access to all data in a record whereas a customer has access only to a subset of that data.
Data validation is applied to fields in forms. Here's a sample form to get you started.
type CatForm struct {
FormBase
Name string `json:"name" validate:"required,min=2,max=50"`
Type string `json:"type" validate:"required,min=2,max=80"`
}
func (form *CatForm) MapToModel() *Cat {
return &Cat{
Name: form.Name,
Type: form.Type,
}
}
The FormBase
struct provides the ID
, CreatedAt
and UpdatedAt
fields.
Each field should specify the name mapping in JSON format along with validation rules. For more on validations check out the Playground Validator documentation. To skip validations all together, use validate:"-"
.
Finally, each form should have a MapToModel()
function that returns a model, so it can be stored after it has been validated. Note that forms do not set a model's ID
property as that is the job of the model. Instead, it must be set manually prior to a database operation. Think of this like an actual form you fill up that has a section "for office use only".