When building REST API or web applications using Go, an essential part is to validate the incoming request data. I have worked in some small and medium project in Golang, most of them are micro-services, providing restful api. I have used different way to validate incoming data. Lets start with particular one that I use frequently. For validating application/json or text/plain request, first I build a struct type of that particular request and add a validate method on the struct. Lets see an example:

This is my first choice when accepting json payload, but for form-data, query string or x-www-form-urlencoded , its little bit different. For complex validation generally I use: https://github.com/asaskevich/govalidator , but some times it took more time for validating the request other than writing the business logic. When a validation rules change you have to rewrite the message also. To avoid this, I have build a simple validator package for golang request validation. Lets see how it works:

This is little bit cleaner and simple, when you need to modify the rules you can do it easily. What if you need a custom validation rule, for example you are asking for a rule where you can check unique username. You can add your custom rule easily. Lets see an example of adding a custom rules:

It’s straightforward to add a custom rule, but I’m still experimenting with the request validation process. Using struct tags or strings for validation rules doesn’t seem sufficient. I hope a better solution for validating incoming requests will emerge in the future. I’d love to hear your thoughts on the validation process and what approaches you prefer.