一、基本示例 1、validator介绍
2、Json数据解析和绑定 package main
import ( 'github.com/gin-gonic/gin' 'net/http' )
// 定义接收数据的结构体 type Login struct { // binding:'required'修饰的字段,若接收为空值,则报错,是必须字段 User string `form:'username' json:'user' uri:'user' xml:'user' binding:'required'` Pssword string `form:'password' json:'password' uri:'password' xml:'password' binding:'required'` }
func main() { // 1.创建路由 // 默认使用了2个中间件Logger(), Recovery() r := gin.Default() // JSON绑定 r.POST('loginJSON', testHandler) r.Run(':8000') }
func testHandler(c *gin.Context) { // 声明接收的变量 var json Login // 将request的body中的数据,自动按照json格式解析到结构体 if err := c.ShouldBindJSON(&json); err != nil { // 返回错误信息 // gin.H封装了生成json数据的工具 c.JSON(http.StatusBadRequest, gin.H{'error': err.Error()}) return } // 判断用户名密码是否正确 if json.User != 'root' || json.Pssword != 'root' { c.JSON(http.StatusBadRequest, gin.H{'status': '304'}) return } c.JSON(http.StatusOK, gin.H{'status': '200'}) }
3、表单数据解析和绑定
<!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>Document</title> </head> <body> <form action='http://localhost:8000/loginForm' method='post' enctype='application/x-www-form-urlencoded'> 用户名<input type='text' name='username'><br> 密码<input type='password' name='password'> <input type='submit' value='提交'> </form> </body> </html> 4、URL数据解析和绑定
二、结构体验证
1、main.go package main import ( 'fmt' 'time' 'github.com/gin-gonic/gin' )
//Person .. type Person struct { //不能为空并且大于10 Age int `form:'age' binding:'required,gt=10'` Name string `form:'name' binding:'required'` Birthday time.Time `form:'birthday' time_format:'2006-01-02' time_utc:'1'` }
func main() { r := gin.Default() r.GET('/5lmh', func(c *gin.Context) { var person Person if err := c.ShouldBind(&person); err != nil { c.String(500, fmt.Sprint(err)) return } c.String(200, fmt.Sprintf('%#v', person)) }) r.Run() } 2、测试
三、翻译校验错误提示信息
curl -H 'Content-type: application/json' -X POST -d '{'name':'q1mi','age':18,'email':'123.com'}' http://127.0.0.1:8999/signup
四、自定义验证 package main
import ( 'net/http' 'reflect' 'github.com/gin-gonic/gin' 'github.com/gin-gonic/gin/binding' 'gopkg.in/go-playground/validator.v8' )
/* 对绑定解析到结构体上的参数,自定义验证功能 比如我们要对 name 字段做校验,要不能为空,并且不等于 admin ,类似这种需求,就无法 binding 现成的方法 需要我们自己验证方法才能实现 官网示例(https:///gopkg.in/go-playground/validator.v8#hdr-Custom_Functions) 这里需要下载引入下 gopkg.in/go-playground/validator.v8 */ type Person struct { Age int `form:'age' binding:'required,gt=10'` // 2、在参数 binding 上使用自定义的校验方法函数注册时候的名称 Name string `form:'name' binding:'NotNullAndAdmin'` Address string `form:'address' binding:'required'` }
// 1、自定义的校验方法 func nameNotNullAndAdmin(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { if value, ok := field.Interface().(string); ok { // 字段不能为空,并且不等于 admin return value != '' && !('5lmh' == value) } return true }
func main() { r := gin.Default()
// 3、将我们自定义的校验方法注册到 validator中 if v, ok := binding.Validator.Engine().(*validator.Validate); ok { // 这里的 key 和 fn 可以不一样最终在 struct 使用的是 key v.RegisterValidation('NotNullAndAdmin', nameNotNullAndAdmin) }
/* curl -X GET 'http://127.0.0.1:8080/testing?name=&age=12&address=beijing' curl -X GET 'http://127.0.0.1:8080/testing?name=lmh&age=12&address=beijing' curl -X GET 'http://127.0.0.1:8080/testing?name=adz&age=12&address=beijing' */ r.GET('/5lmh', func(c *gin.Context) { var person Person if e := c.ShouldBind(&person); e == nil { c.String(http.StatusOK, '%v', person) } else { c.String(http.StatusOK, 'person bind err:%v', e.Error()) } }) r.Run() } |
|