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

  • Go Web Development Cookbook
  • Arpit Aggarwal
  • 283字
  • 2021-08-27 19:01:19

How to do it…

  1. Install github.com/asaskevich/govalidator and the github.com/gorilla/schema package using the go get command, as follows:
$ go get github.com/asaskevich/govalidator
$ go get github.com/gorilla/schema
  1. Create html-form-validation.go, where we will read an HTML form, decode it using github.com/gorilla/schema, and validate each field of it against a tag defined in the User struct using github.com/asaskevich/govalidator, as follows:
package main
import
(
"fmt"
"html/template"
"log"
"net/http"
"github.com/asaskevich/govalidator"
"github.com/gorilla/schema"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
USERNAME_ERROR_MESSAGE = "Please enter a valid Username"
PASSWORD_ERROR_MESSAGE = "Please enter a valid Password"
GENERIC_ERROR_MESSAGE = "Validation Error"
)
type User struct
{
Username string `valid:"alpha,required"`
Password string `valid:"alpha,required"`
}
func readForm(r *http.Request) *User
{
r.ParseForm()
user := new(User)
decoder := schema.NewDecoder()
decodeErr := decoder.Decode(user, r.PostForm)
if decodeErr != nil
{
log.Printf("error mapping parsed form data to struct : ",
decodeErr)
}
return user
}
func validateUser(w http.ResponseWriter, r *http.Request, user *User) (bool, string)
{
valid, validationError := govalidator.ValidateStruct(user)
if !valid
{
usernameError := govalidator.ErrorByField(validationError,
"Username")
passwordError := govalidator.ErrorByField(validationError,
"Password")
if usernameError != ""
{
log.Printf("username validation error : ", usernameError)
return valid, USERNAME_ERROR_MESSAGE
}
if passwordError != ""
{
log.Printf("password validation error : ", passwordError)
return valid, PASSWORD_ERROR_MESSAGE
}
}
return valid, GENERIC_ERROR_MESSAGE
}
func login(w http.ResponseWriter, r *http.Request)
{
if r.Method == "GET"
{
parsedTemplate, _ := template.ParseFiles("templates/
login-form.html")
parsedTemplate.Execute(w, nil)
}
else
{
user := readForm(r)
valid, validationErrorMessage := validateUser(w, r, user)
if !valid
{
fmt.Fprintf(w, validationErrorMessage)
return
}
fmt.Fprintf(w, "Hello "+user.Username+"!")
}
}
func main()
{
http.HandleFunc("/", login)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
  1. Run the program with the following command:
$ go run html-form-validation.go
主站蜘蛛池模板: 霍城县| 启东市| 房产| 卢湾区| 株洲市| 彭山县| 济南市| 诸城市| 中方县| 乌兰察布市| 徐水县| 富宁县| 胶州市| 卓尼县| 合山市| 珲春市| 巩留县| 松溪县| 霸州市| 团风县| 西乌珠穆沁旗| 麟游县| 花垣县| 中西区| 丰镇市| 彭泽县| 鲁甸县| 根河市| 北海市| 静乐县| 无为县| 祁东县| 会东县| 衡山县| 龙岩市| 长乐市| 板桥市| 囊谦县| 泽普县| 冕宁县| 梁山县|