官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 五寨县| 招远市| 安图县| 张家川| 屏南县| 团风县| 乌恰县| 舒兰市| 昭苏县| 漳州市| 和田市| 望江县| 广昌县| 翁牛特旗| 奉新县| 耒阳市| 潜山县| 米林县| 长宁县| 鸡东县| 琼结县| 来安县| 茶陵县| 兴隆县| 张家港市| 边坝县| 龙口市| 余庆县| 峨山| 霍州市| 沙河市| 泗阳县| 长武县| 凤冈县| 嘉禾县| 伊通| 横山县| 方城县| 岢岚县| 双流县| 宜昌市|