当前位置:网站首页>Getting started with go web programming: validators
Getting started with go web programming: validators
2022-06-22 00:26:00 【InfoQ】
Preface
Manually verify the input
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")
}Use the structure tag to validate the input

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 Fields should not be set by the user , So we verify that it has int The default value of , namely 0
- FullName and LastName It's necessary
- Email fields are required , And use a predefined email validator to verify
Use a custom validator to validate input
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"`
}Recommended validation Libraries

- 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.
summary
- Package validatorValidation
- Awesome Go:https://awesome-go.com/validation/
- Client-side form validation
- Validate REST Input in Go
- Verification of inputs
边栏推荐
- MySQL性能分析工具的使用
- The difference between overloading and overriding
- Brève idée et cas simple de l'ajustement JVM - mécanisme de garantie de l'allocation de l'espace dans les temps anciens
- Meet webassembly again
- ARM32指令解析通用寄存器
- 你有一个机会,这里有一个舞台
- [RoarCTF2019]黄金6年
- 客户端建设及调优实践
- 如何优雅的统计代码耗时
- [Yugong series] general responsibility allocation principle in June 2022 (IX) - principle of protected variables
猜你喜欢

Meet webassembly again
![[roarctf2019] gold 6 years](/img/c4/07caf5dc8f27f77b724753b5f87a0a.png)
[roarctf2019] gold 6 years
![[pwn basics]pwntools learning](/img/72/0f80d2f91d772e361b6d23a67e2ca3.png)
[pwn basics]pwntools learning
![[next] the component definition is missing display name in the next JS package](/img/19/2da1ea19987959f8636aa1dbbaae26.png)
[next] the component definition is missing display name in the next JS package

程序员坐牢了,会被安排去写代码吗?

metersphere与jenkins的持续集成

【next】nextjs打包出现组件定义缺少显示名称【Component definition is missing display name】
![[RoarCTF2019]黄金6年](/img/c4/07caf5dc8f27f77b724753b5f87a0a.png)
[RoarCTF2019]黄金6年

katalon Recoder常用命令

Go Web 编程入门:验证器
随机推荐
数据魔术师告诉你整数规划COPT5.0离CPLEX还有多远?
[Yugong series] general responsibility allocation principle in June 2022 (IX) - principle of protected variables
Client construction and Optimization Practice
anaconda历史版本下载
关于 NFT 和版权的纠结真相
Mathematical knowledge: sum of divisors - divisors
[GXYCTF2019]SXMgdGhpcyBiYXNlPw==
【微信小程序】40029 invalid code解决办法集合
数学知识:约数之和—约数
Buuctf misc weak password
Recruitment brochure for traditional product manager international qualification certification (NPDP) in the second half of 2022
Copy and paste in terminal, 0~ and 1~ characters are added
discuz!论坛修复站帮网vip插件bug:VIP会员到期后,重新开通永久会员时,所属的用户组没有切换到永久会员分组
一文看尽物体检测中的各种FPN
数学知识:约数个数—约数
Shenzhen Data Analyst Certification (CPDA) in the second half of 2022, [enter to view]
嵌入式系统、嵌入式设计软件概述
【node】node使用mysql连接池
[next] the component definition is missing display name in the next JS package
MNIST image classification and comparison based on K-nearest neighbor