An overview of the
While the previous article shared that the Gin framework uses Logrus for logging, this article shares the data binding and validation of the Gin framework.
A reader asked me a question, how to make the framework run logs do not output to the console?
Solution:
Engine := gin.default () engine := gin.new ()Copy the code
How do I know that? Look at the framework code.
The Default () :
func Default() *Engine {
debugPrintWARNINGDefault()
engine := New()
engine.Use(Logger(), Recovery())
return engine
}
Copy the code
I’m not going to post the New() code.
We see that Default() uses two middleware Loggers () and Recovery(). If you don’t want to use them, you can just use New().
Start today’s article.
For example, request v1/member/add to add member method, name, age must be mandatory, and name cannot be equal to admin string, 10 <= age <= 120.
Just look at the code.
First, define a structure.
entity/member.go
Package Entity // Defines the Member structuretype Member struct {
Name string `form:"name" json:"name" binding:"required,NameValid"`
Age int `form:"age" json:"age" binding:"required,gt=10,lt=120"`}Copy the code
Required in the binding, which comes with the framework, NameValid, which is self-defined.
Question 1: What other binding parameters do the framework have?
Question 2: How to write a custom validation method?
The next step is problem two, which is to write a validation method.
validator/member/member.go
package member
import (
"gopkg.in/go-playground/validator.v8"
"reflect"
)
func NameValid(
v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
) bool {
if s, ok := field.Interface().(string); ok {
if s == "admin" {
return false}}return true
}
Copy the code
Next, bind in the route:
router/router.go
package router
import (
"ginDemo/middleware/logger"
"ginDemo/middleware/sign"
"ginDemo/router/v1"
"ginDemo/router/v2"
"ginDemo/validator/member"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"gopkg.in/go-playground/validator.v8") func InitRouter(r *gin.Engine) {r.Use(logger.loggertofile ()) // v1 version GroupV1 := r.roup ("/v1")
{
GroupV1.Any("/product/add", v1.AddProduct)
GroupV1.Any("/member/add"AddMember)} // GroupV2 := r.group ("/v2").Use(sign.Sign())
{
GroupV2.Any("/product/add", v2.AddProduct)
GroupV2.Any("/member/add", v2.addmember)} // Bind the validatorif v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("NameValid", member.NameValid)
}
}
Copy the code
Finally, take a look at the calling code.
router/v1/member.go
package v1
import (
"ginDemo/entity"
"github.com/gin-gonic/gin"
"net/http"
)
func AddMember(c *gin.Context) {
res := entity.Result{}
mem := entity.Member{}
iferr := c.ShouldBind(&mem); err ! = nil { res.SetCode(entity.CODE_ERROR) res.SetMessage(err.Error()) c.JSON(http.StatusForbidden, res) c.Abort()returnData := map[string]interface{}{"name" : mem.Name,
"age" : mem.Age,
}
res.SetCode(entity.CODE_ERROR)
res.SetData(data)
c.JSON(http.StatusOK, res)
}
Copy the code
Visit to see what happens.
Visit: http://localhost:8080/v1/member/add
{
"code": 1,"msg": "Key: 'Member.Name' Error:Field validation for 'Name' failed on the 'required' tag\nKey: 'Member.Age' Error:Field validation for 'Age' failed on the 'required' tag"."data": null
}
Copy the code
Visit: http://localhost:8080/v1/member/add? name=1
{
"code": 1,"msg": "Key: 'Member.Age' Error:Field validation for 'Age' failed on the 'required' tag"."data": null
}
Copy the code
Visit: http://localhost:8080/v1/member/add? age=1
{
"code": 1,"msg": "Key: 'Member.Age' Error:Field validation for 'Age' failed on the 'required' tag"."data": null
}
Copy the code
Visit: http://localhost:8080/v1/member/add? name=admin&age=1
{
"code": 1,"msg": "Key: 'Member.Name' Error:Field validation for 'Name' failed on the 'NameValid' tag"."data": null
}
Copy the code
Visit: http://localhost:8080/v1/member/add? name=1&age=1
{
"code": 1,"msg": "Key: 'Member.Age' Error:Field validation for 'Age' failed on the 'gt' tag"."data": null
}
Copy the code
Visit: http://localhost:8080/v1/member/add? name=1&age=121
{
"code": 1,"msg": "Key: 'Member.Age' Error:Field validation for 'Age' failed on the 'lt' tag"."data": null
}
Copy the code
Visit: http://localhost:8080/v1/member/add? name=Tom&age=30
{
"code": 1,
"msg": ""."data": {
"age": 30."name": "Tom"}}Copy the code
Not to avoid returning too much information, error prompts we can also be unified.
iferr := c.ShouldBind(&mem); err ! = nil { res.SetCode(entity.CODE_ERROR) res.SetMessage("Parameter validation error")
c.JSON(http.StatusForbidden, res)
c.Abort()
return
}
Copy the code
This time the directory structure has been tweaked a bit, here it is:
├ ─ ginDemo │ ├ ─ common / / public methods │ ├ ─ ─ common. Go │ ├ ─ config / / configuration file │ ├ ─ ─ config. Go │ ├ ─ the entity / / entity │ ├ ─ ─... │ ├─ Logger │ ├─... │ ├─ Sign │ ├─... │ ├─ Heavy Metal Exercises │ ├─ Heavy Metal Exercises │ ├─ Heavy Metal Exercises │ ├─ Heavy Metal Exercises │ ├─ Vendor // Extension │ ├─ Github.com │ ├─... │ ├─ Heavy Metal Exercises │ ├─ Heavy Metal Exercises │ ├── Bass Exercises. In │ ├─... │ ├─ Bass Exercises. Toml │ ├─ Bass Exercises. Lock │ ├─ MainCopy the code
Make the Sign and Logger middleware and put them in the Middleware directory.
Added the common methods directory.
Added the Validator directory.
The Entity entity directory is added.
I will put the specific code on GitHub, if you are interested, you can go to github.com/xinliangnot…
What are the binding parameters that come with the framework?
From the source code of the framework, we know that the validation uses:
gopkg.in/go-playground/validator.v8
The document address is:
Godoc.org/gopkg.in/go…
Explore the documentation, which is full of validation rules.
Recommended reading
Gin framework
- Gin framework – Data binding and validation
- Gin framework – Use Logrus logging
- Gin framework – Installation and routing configuration
Based on article
- Go – function
- Go – cycle
- Go-map collection
- Go-struct structure
- Go-slice Slice
- Go – array
- Go – Variable declaration
- Go-environment installation
This article is welcome to forward, forward please indicate the author and source, thank you!