当前位置:网站首页>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
边栏推荐
- 【next】nextjs打包后出现passHref is missing
- 关于一次Web线下面试的思考
- 【php】mvcs概念(通俗易懂)
- 【taro】taro微信小程序input在苹果手机上光标聚焦不对的解决办法
- American tourist visa interview instructions, let me focus!
- Implementation and tuning of decision tree (sklearn, gridsearchcv)
- Katalon framework testing web (XVIII) framework operation
- Continuous integration of metersphere and Jenkins
- AttributeError: ‘WebDriver‘ object has no attribute ‘w3c‘
- Introduction to activities in the name of the father (you can collect sheep)
猜你喜欢

buuctf misc zip

Oracle flashback and RMAN samples

Client construction and Optimization Practice

如何使用tensorboard add_histogram

Win10使用用户初始密码,连接Win Server失败

Lectures explanation for unsupervised graph level representation learning (usib)

WMS warehouse management system source code

Neural networks and support vector machines for machine learning

Qt之自制MP3播放器

关于 NFT 和版权的纠结真相
随机推荐
Xshell连接虚拟机只能输入public key解决方案【亲测】
The minimum non composable sum of arrays
【php】mvcs概念(通俗易懂)
【微信小程序】40029 invalid code解决办法集合
存储api备忘录
SQL tutorial: five SQL skills that data scientists need to master
未定义UNICODE_STRING 标识解决方案
[sword finger offer] 43 Number of occurrences of 1 in integers 1 to n
[wechat applet] 40029 invalid code solution set
你有一个机会,这里有一个舞台
JVM makes wheels
Buuctf misc weak password
诚邀 Elastic Stack 开发者成为 CSDN Elastic 云社区管理员
【微信小程序】微信小程序使用表单的一些坑和注意事项
[wechat applet] obtain the current geographic latitude and IP address
美国旅游签证面试须知,我来敲重点啦!
Katalon framework testing web (XVIII) framework operation
Mathematical knowledge: number of approximations - approximations
SQL interview questions: top 15 questions in 2022
JVM调优简要思想及简单案例-老年代空间分配担保机制