当前位置:网站首页>Go Web 编程入门:验证器
Go Web 编程入门:验证器
2022-06-21 22:51:00 【InfoQ】
前言
手动验证输入
gorilla/mux/userpackage main
import (
"encoding/json"
"log"
"net/http"
"strings"
"github.com/gorilla/mux"
)
type User struct {
ID int
FirstName string
LastName string
FavouriteVideoGame string
Email string
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/user", PostUser).Methods(http.MethodPost)
router.HandleFunc("/user", GetUsers).Methods(http.MethodGet)
log.Fatal(http.ListenAndServe(":8081", router))
}
var users = []User{}
var id = 0
func validateEmail(email string) bool {
// This is obviously not a good validation strategy for email addresses
// pretend a complex regex here
return !strings.Contains(email, "@")
}
func PostUser(w http.ResponseWriter, r *http.Request) {
user := User{}
json.NewDecoder(r.Body).Decode(&user)
// We don't want an API user to set the ID manually
// in a production use case this could be an automatically
// ID in the database
user.ID = id
id++
users = append(users, user)
w.WriteHeader(http.StatusCreated)
}
func GetUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(users); err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
} if len(r.Form["username"][0])==0{
// code for empty field
}if user.FirstName == "" {
errs = append(errs, fmt.Errorf("Firstname is required").Error())
}
if user.LastName == "" {
errs = append(errs, fmt.Errorf("LastName is required").Error())
}
if user.Email == "" || validateEmail(user.Email) {
errs = append(errs, fmt.Errorf("A valid Email is required").Error())
}package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/gorilla/mux"
)
type User struct {
ID int
FirstName string
LastName string
FavouriteVideoGame string
Email string
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/user", PostUser).Methods(http.MethodPost)
router.HandleFunc("/user", GetUsers).Methods(http.MethodGet)
log.Fatal(http.ListenAndServe(":8081", router))
}
var users = []User{}
var id = 0
func validateEmail(email string) bool {
// That's obviously not a good validation strategy for email addresses
// pretend a complex regex here
return !strings.Contains(email, "@")
}
func PostUser(w http.ResponseWriter, r *http.Request) {
user := User{}
json.NewDecoder(r.Body).Decode(&user)
errs := []string{}
if user.FirstName == "" {
errs = append(errs, fmt.Errorf("Firstname is required").Error())
}
if user.LastName == "" {
errs = append(errs, fmt.Errorf("LastName is required").Error())
}
if user.Email == "" || validateEmail(user.Email) {
errs = append(errs, fmt.Errorf("A valid Email is required").Error())
}
if len(errs) > 0 {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(errs); err != nil {
}
return
}
// We don't want an API user to set the ID manually
// in a production use case this could be an automatically
// ID in the database
user.ID = id
id++
users = append(users, user)
w.WriteHeader(http.StatusCreated)
}
func GetUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(users); err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}validateEmail@func validateEmail(email string) bool {
// That's obviously not a good validation strategy for email addresses
// pretend a complex regex here
return !strings.Contains(email, "@")
} if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, r.Form.Get("email")); !m {
fmt.Println("no")
}else{
fmt.Println("yes")
}使用结构标签验证输入

go get github.com/go-playground/validator/v10package main
import (
"encoding/json"
"log"
"net/http"
"github.com/go-playground/validator/v10"
"github.com/gorilla/mux"
)
type User struct {
ID int `validate:"isdefault"`
FirstName string `validate:"required"`
LastName string `validate:"required"`
FavouriteVideoGame string
Email string `validate:"required,email"`
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/user", PostUser).Methods(http.MethodPost)
router.HandleFunc("/user", GetUsers).Methods(http.MethodGet)
log.Fatal(http.ListenAndServe(":8081", router))
}
var users = []User{}
var id = 0
func PostUser(w http.ResponseWriter, r *http.Request) {
user := User{}
json.NewDecoder(r.Body).Decode(&user)
validate := validator.New()
err := validate.Struct(user)
if err != nil {
validationErrors := err.(validator.ValidationErrors)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
responseBody := map[string]string{"error": validationErrors.Error()}
if err := json.NewEncoder(w).Encode(responseBody); err != nil {
}
return
}
// We don't want an API user to set the ID manually
// in a production use case this could be an automatically
// ID in the database
user.ID = id
id++
users = append(users, user)
w.WriteHeader(http.StatusCreated)
}
func GetUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(users); err != nil {
log.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}validationError.Error()- ID 字段不应该由用户设置,所以我们验证它有 int 的默认值,即 0
- FullName 和 LastName 是必需的
- 电子邮件字段是必需的,并使用预定义的电子邮件验证器进行验证
使用自定义验证器验证输入
func GameBlacklistValidator(f1 validator.FieldLevel) bool {
gameBlacklist := []string{"PUBG", "Fortnite"}
game := f1.Field().String()
for _, g := range gameBlacklist {
if game == g {
return false
}
}
return true
}...
validate := validator.New()
validate.RegisterValidation("game-blacklist", GameBlacklistValidator)
...type User struct {
ID int `validate:"isdefault"`
FirstName string `validate:"required"`
LastName string `validate:"required"`
FavouriteVideoGame string `validate:"game-blacklist"`
Email string `validate:"required,email"`
}推荐验证库

- checkdigit - Provide check digit algorithms (Luhn, Verhoeff, Damm) and calculators (ISBN, EAN, JAN, UPC, etc.).
- gody - :balloon: A lightweight struct validator for Go.
- govalid - Fast, tag-based validation for structs.
- govalidator - Validators and sanitizers for strings, numerics, slices and structs.
- govalidator - Validate Golang request data with simple rules. Highly inspired by Laravel’s request validation.
- jio - jio is a json schema validator similar to joi.
- ozzo-validation - Supports validation of various data types (structs, strings, maps, slices, etc.) with configurable and extensible validation rules specified in usual code constructs instead of struct tags.
- terraform-validator - A norms and conventions validator for Terraform.
- validate - Go package for data validation and filtering. support validate Map, Struct, Request(Form, JSON, url.Values, Uploaded Files) data and more features.
- validate - This package provides a framework for writing validations for Go applications.
- validator - Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving.
- Validator - A lightweight model validator written in Go.Contains VFs:Min, Max, MinLength, MaxLength, Length, Enum, Regex.
总结
- Package validatorValidation
- Awesome Go:https://awesome-go.com/validation/
- Client-side form validation
- Validate REST Input in Go
- Verification of inputs
边栏推荐
- 微博关闭发布多个兼职诈骗信息违规账号:如何打击数据造假灰产
- 微服务测试效率治理
- Component value transfer: value transfer between siblings (value transfer by non parent and child components)
- 你有一个机会,这里有一个舞台
- buuctf misc 间谍启示录
- [set static route] "WiFi for private internal network and external network“
- JVM调优简要思想及简单案例-老年代空间分配担保机制
- [typescript] the difference between exclamation mark and question mark in typescript
- Buuctf misc spy Apocalypse
- 【node】node使用mysql连接池
猜你喜欢

Hotline salon issue 26 - cloud security session

CPDA | what basic skills do data analysts need?

Binary sort tree

Introduction to activities in the name of the father (you can collect sheep)

Xshell连接虚拟机只能输入public key解决方案【亲测】
![[taro] the solution of taro wechat applet input focusing the cursor incorrectly on the Apple phone](/img/67/6f46d415475d024950e2502c1f5dc2.png)
[taro] the solution of taro wechat applet input focusing the cursor incorrectly on the Apple phone
![[actf freshman competition 2020]swp](/img/80/9fe85ee614857c5800c0d0b1ba9a3d.png)
[actf freshman competition 2020]swp
![[an Xun cup 2019] blowing bass to sweep QR code](/img/38/7bfa5e9b97658acfe24d3aab795bce.png)
[an Xun cup 2019] blowing bass to sweep QR code

En juin, le classement des langues de programmation a été publié et la langue doit être « féodale ».

Nearly 90% of servers can be saved, but the anti fraud efficiency has greatly increased. Why is PayPal's plan to break the "Ai memory wall" so cost-effective?
随机推荐
En juin, le classement des langues de programmation a été publié et la langue doit être « féodale ».
Appium gets the exception of displaying spaces in the middle of object text through XPath
微服务测试效率治理
从云鲸率先布局上门服务,看其如何用服务冲破行业“封锁线”
Detailed explanation of IDA static reverse analysis tool
HMS core machine learning service ID card identification function to achieve efficient information entry
以父之名活动攻略(可以薅羊毛啦)
[wechat applet] obtain the current geographic latitude and IP address
[set static route] "WiFi for private internal network and external network“
Object划分
[next] passhref is missing appears after nextjs is packaged
pytorch 界面编程相关
[sword finger offer] 43 Number of occurrences of 1 in integers 1 to n
vim自动命令事件大全
[typescript] the difference between exclamation mark and question mark in typescript
【愚公系列】2022年06月 通用职责分配原则(九)-受保护变量原则
Six little-known SQL technologies in SQL tutorial can help you save 100 hours per month
pytorch可视化
微博关闭发布多个兼职诈骗信息违规账号:如何打击数据造假灰产
metersphere与jenkins的持续集成