Go Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

How it works…

Once we run the program, the HTTP server will start locally listening on port 8080. Browsing http://localhost:8080 will show us an HTML form, as shown in the following screenshot:

Then submit the form with the valid values:

It will show us the Hello followed by the username on a browser screen, as shown in the following screenshot:

Submitting the form with the value as non-alpha in any of the fields will show us the error message. For example, submitting the form with the Username value as 1234:

It will show us an error message on the browser, as shown in the following screenshot:

Moreover, we can submit an HTML form from the command line as:

$ curl --data "username=Foo&password=password" http://localhost:8080/

This will give us the same output that we get in the browser:

Let’s understand the change we introduced in this recipe:

  1. Using import ("fmt", "html/template", "log", "net/http" "github.com/asaskevich/govalidator" "github.com/gorilla/schema" ), we imported an additional package—github.com/asaskevich/govalidator, which helps us to validate structs.
  1. Next, we updated the User struct type to include a string literal tag with the key as valid and value as alpha, required, as follows:
type User struct 
{
Username string `valid:"alpha,required"`
Password string
valid:"alpha,required"
}
  1. Next, we defined a validateUser handler, which takes ResponseWriter, Request, and User as inputs and returns a bool and string, which are the struct valid status and validation error message respectively. In this handler, we validated struct tags calling the ValidateStruct handler from govalidator. If there is an error in validating the field, then we fetch the error calling the ErrorByField handler from govalidator and return the result along with the validation error message.
  2. Next, we updated the login handler to call validateUser passing (w http.ResponseWriter, r *http.Request, user *User) as input parameters to it and check for any validation errors. If there are errors, then we write an error message to an HTTP response stream and return it.