Implement data validation in Go

WBOY
發布: 2024-08-19 12:31:20
原創
582 人瀏覽過

Implement data validation in Go

Data validation is an important part of software development. It makes sure that input data is accurate and meets the requirements before processing or storing it. In Go, data validation is simple and flexible.

This guide will teach you how to use struct tags to validate data and make your apps safe and reliable. From creating validation logic to using built-in validation tags.

Prerequisites

  • Go 1.21

Setup project

Setting up the Go project dependencies.

go mod init app go get github.com/gin-gonic/gin
登入後複製

Project structure

├─ main.go ├─ models │ └─ user.go └─ public └─ index.html
登入後複製

Project files

user.go

The User struct is designed for testing validation within the application, incorporating validation tags to enforce specific rules.

package models type User struct { Id int `binding:"required" msg:"Required"` Name string `binding:"max=10" msg:"Maximum length is 10"` Email string `binding:"email" msg:"Invalid email address"` Age int `binding:"min=1,max=100" msg:"Must between 1 and 100"` BirthDate string `binding:"datetime=01/02/2006" msg:"Invalid date format"` }
登入後複製

Since the default error messages are not user-friendly, we added a custom msg tag to define more meaningful error messages.

main.go

This file is the main entry point for our application. It will create and set up the minimal Go web application.

package main import ( "app/models" "net/http" "reflect" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" ) func main() { router := gin.Default() router.LoadHTMLFiles("public/index.html") router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", nil) }) router.POST("/", func(c *gin.Context) { var user models.User if err := c.ShouldBind(&user); err != nil { c.HTML(http.StatusOK, "index.html", gin.H{"User": user, "Errors": getErrors(err, user)}) return } c.HTML(http.StatusOK, "index.html", gin.H{"Pass": true, "User": user}) }) router.Run() } func getErrors(err error, obj any) map[string]string { messages := getMessages(obj) errors := map[string]string{} for _, e := range err.(validator.ValidationErrors) { errors[e.Field()] = messages[e.Field()] } return errors } func getMessages(obj any) map[string]string { t := reflect.TypeOf(obj) messages := map[string]string{} for i := 0; i < t.NumField(); i++ { field := t.Field(i) messages[field.Name] = field.Tag.Get("msg") } return messages }
登入後複製
  • GET method to return the input form.
  • POST method for form submission and validation of user input.
  • getErrors() returns the error information.
  • getMessages() leverages our custom msg tag to retrieve error messages for specific fields.

index.html

The HTML user input form is designed to test the validation rules applied to the User struct. It typically includes fields that correspond to the properties of the User struct.

       
{{if .Errors.Id}}{{.Errors.Id}}{{end}}
{{if .Errors.Name}}{{.Errors.Name}}{{end}}
{{if .Errors.Email}}{{.Errors.Email}}{{end}}
{{if .Errors.Age}}{{.Errors.Age}}{{end}}
{{if .Errors.BirthDate}}{{.Errors.BirthDate}}{{end}}
{{if .Pass}}
Validation success!
{{end}}
登入後複製

We use Go's HTML template syntax, such as {{if .Errors.Id}}, to display error messages to the user.

Run project

go run main.go
登入後複製

Open the web browser and goto http://localhost:8080

You will find this test page.

Implement data validation in Go

Testing

Click "Fill invalid data" and then click "Submit" to see the error messages displayed in the input form.

Implement data validation in Go

Click "Fill valid data" and then "Submit" again. You should see the validation success message displayed in the input form.

Implement data validation in Go

Conclusion

This article has covered implementing the basic data validation, helping you build reliable and user-friendly applications. Apply these practices to enhance both the robustness and usability of your Go web application.

Source code: https://github.com/stackpuz/Example-Validation-Go

Create a CRUD Web App in Minutes: https://stackpuz.com

以上是Implement data validation in Go的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!