At this stage we will add validation for each request sent to the API Application on our Services for example on add, change and delete requests. The validation we use is package github.com/go-playground/validator.
If we look at the documentation, there is a function that we will use in the package by checking the struct that we will validate.
err := validate.Struct(myStruct)
validateErrors := err(.Validator.ValidationErrors)
Then we need to add some tags to the fields in the struct that we will validate.
Adding Dependency Validator
First we add the validator package that we will need to the project by using the module golang.
go get github.com/go-playground/validator/v10
Then import the validator package into the code we are using
import "github.com/go-playground/validator/v10"
Adding Validation to Struct
In the create article request there are several validations that we must apply by adding to the struct create request as below.
type ArticleCreateRequest struct {
Title string `validate: "required,max=160,min=0"`
Content string `validate: "required"`
CreateAt time.Time
}
Next, add a request to the article update request
type ArticleUpdateRequest struct {
ID int64 `validate: "required"`
Title string `validate: "required,max=160,min=0"`
Content string `validate: "required"`
UpdateAt time.Time
}
After the struct adds validators to each of the fields that need validation, we then add the validator initialization to the handler.
type Delivery struct {
articleUsecase usecase.ArticleUsecase
validate *validator.Validate
}
func New(articleUsecase usecase.ArticleUsecase) *Delivery {
return &Delivery{
articleUsecase: articleUsecase,
validate: validator.New(),
}
}
And add struct validation to the Create
and Update
functions in the position handler before accessing the usecase layer.
func (d *Delivery) Store(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
...
...
err = d.validate.Struct(request)
if err != nil {
response.Code = http.StatusBadRequest
response.Status = err.Error()
}
...
...
}
And in the Update
function we also add a handler like this.
func (d *Delivery) Update(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
...
...
err = d.validate.Struct(request)
if err != nil {
response.Code = http.StatusBadRequest
response.Status = err.Error()
}
...
...
}
All the functions that we need to validate requests have been implemented so that when there is a request from the user this validator works so that the form fields in the struct do not contain blanks and according to the rules that have been determined by us.