Input Validation in Golang Web Applications

Abu Bakkar Siddique
4 min readApr 13, 2021

Validation is a very important part of any web application that deals with user input. So in this article, I am going to share my experience of handling validation of user data that we get from http requests. Let’s start.

First, let’s create a small web application. Create a new directory and open it in your favorite code editor. I am going to use VS Code.

Open the terminal and go inside the directory you have created for your application. Now we are going to create a go module using the following command.

Here you can use your remote repository path after the go mod init command.

Now let’s create a new file called main.go and add the following code in it.

In this code we are just creating a simple http server which will handle a POST request on /register path. Now we are going to read data from request body and store it in a struct. Let’s create a struct with a name NewUser that we can use to save request data.

Let’s now read our request body and store data in this struct. Write the following code.

Now we are going to get a validation library from the following URL.

This library will help us validate struct fields very easily. To make NewUser struct validatable, it needs to implement CanValidate interface provided by the library. There is only one method we need to implement from this interface which is Validation() (RuleMap, MessageMap) . So let’s do it now. Write the following code.

In the code above, we added a Validation() method for NewUser struct and in this method, we are returning rules that will apply on struct fields (using json tag) and custom messages that we want to return for some validation rules on a given field.

Now we are going to run validation on this struct. Write the following code.

In the code above, we are running struct validations using validation.Run(newUser) and getting validation errors and any error that might have occured during the process of validation.

If we have validation errors then we are responding with errors messages as json and if everything is good then we are return the newUser data as json.

Let’s run our application and test our code.

I am going to use postman to make a POST request to my application.

Here you can see in the response, we are getting validation errors and if we provide valid data we will get 200 Status and the data we sent in request.

As you can see, we are getting success response now.

github.com/go4all/validation library makes it very easy to validate struct fields and you can easily use it in your code. You can also create custom validation rules. You can learn more from the Readme.md file in the repo. Thanks for reading it.

--

--