Structural label

Tags defined

A Tag is a string of meta information that a structure associates with a member at compile time and is read at run time by reflection.

A structure tag consists of one or more key-value pairs. Keys and values are separated by colons, and values are enclosed in double quotes. The key-value pairs are separated by a space in the following format:

`key1:"value1" key2:"value2" key3:"value3"... `  // Key-value pairs are separated by Spaces
Copy the code

The key specifies the reflection parse method as follows: JSON (JSON tag) ORM (Beego tag), GORM (GORM tag), Bson (MongoDB tag), form(form tag), binding(form validation tag)

Label options

type Student struct {
    ID   int     `json:"-"`            // This field is not serialized
    Name string  `json:name,omitempy`  // If it is of type zero or null, this field is ignored for serialization
    Age  int     `json:age,string`     // Specify a type, including String, number, and BoolEN
}
Copy the code

Note: Encoding/JSON Official document

JSON label

JSON illustrates

JSON arrays can be used to encode arrays and slices in the Go language; Because a JSON object is a string-to-value mapping, written as a series of name:value pairs, the object type of JSON can be used to encode maps and structures in the Go language.

The process of converting a Go structure slice into JSON is called marshaling, and marshaling is done through the json.marshal function. By default, member names of Go language constructs are used as JSON objects when coding (via the Reflect reflection technique). Only exported structure members are encoded.

If you use a custom member name when encoding a structure slice into JSON, you can do this using the structure member Tag.

JSON label

type User struct {
    ID   int `json:"id"`  // The encoded field name is id
    Name string           // The encoded field is named the custom member Name Name
    age  int              // Unexported fields cannot be encoded
}
Copy the code

Json tags with key names are used to control encoding/ JSON packet encoding and decoding behavior, and encoding/… The other packages below follow this convention as well.

Label options Directions for use
Field not serialized example:json:"-"
omitempy Type zero or null. This field is ignored during serialization.json:",omitempy"Structure field names are used when field names are omitted
type Example To respecify the field type:json:"age,string"

GORM label

The model definition

A model is a standard struct consisting of basic data types and custom types that implement the Scanner and Valuer interfaces and their Pointers or aliases.

GORM defines a gorm.model structure, as follows:

type Model struct {
  ID        uint           `gorm:"primaryKey"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt gorm.DeletedAt `gorm:"index"`
}
Copy the code

Tags with gorM keys follow GORM resolution rules. Gorm supports the following tags. Tag names are case-insensitive and camelCase style is recommended. separated

AUTO_INCREMENT does not take effect when Gorm creates a table

// AUTO_INCREMENT does not take effect
Id  uint64 `gorm:"column:id; primaryKey; type:bigint(20); autoIncrement; Comment: 'primary key' "`
// AUTO_INCREMENT does not take effect
Id  uint64 `gorm:"column:id; type:bigint(20); autoIncrement; Comment: 'primary key' "`
// AUTO_INCREMENT Takes effect GorM automatically sets the database field type based on the field type and sets the primary key
Id  uint64 `gorm:"column:id; autoIncrement; Comment: 'primary key' "` // write AUTO_INCREMENT as well
Copy the code
Label options Directions for use
column Specify the DB column name
type Column data type. The compatible general type is recommended. For example, all databases support bool, int, Uint, float, string, time, bytes and can be used together with other tags.not null,size.autoIncrement… likevarbinary(8)Specifying database data types in this way is also supported. When using the specified database data type, it needs to be the full database data type, such as:MEDIUMINT UNSIGNED not NULL AUTO_INCREMENT
size Specify the column size, for example:size:256
primaryKey Specifies the column primary key
unique Specifying a unique column
default Specify column defaults, string defaults in single quotes, for example:gorm:"default:'cn'"
precision Specifies the precision of the column
scale Specify column size
not null Specifies the column NOT NULL
autoIncrement Specifies the column to grow automatically, not to be matchedprimaryKey,typeUse it at the same time or it won’t work. See aboveknowledgePart of the
autoIncrementIncrement Automatic step size that controls the interval between consecutive records
embedded Nested fields
embeddedPrefix The column name prefix of the embedded field
autoCreateTime Tracing the current time at creation time, forintField, which tracks the second-level timestamp that you can usenano/milliTo track nanosecond and millisecond timestamps, for example:autoCreateTime:nano
autoUpdateTime Track the current time when creating/updating, forintField, which tracks the second-level timestamp that you can usenano/milliTo track nanosecond and millisecond timestamps, for example:autoUpdateTime:milli
index Create an index based on the parameter. Create a compound index if multiple fields use the same nameThe indexFor more details
uniqueIndex withindexSame, but create a unique index
check Create check constraints, for examplecheck:age > 13To see theThe constraintFor more details
<- Set the field write permission,<-:createOnly the creation,<-:updateUpdate only,<-:falseNo write permission,<-Create and update permissions
-> Set the field read permission,->:falseNo read permission
Ignore this field,-No read and write permission
comment Annotations are added to fields at migration time

Example:

// Content model
type Content struct {
    Model
    NewsId   uint64  `gorm:"column:news_id"`
    Content  string  `gorm:"column:content"`
}
Copy the code

Custom unique index for knowledge points

// Go version: GO1.16.6 Gorm version: V1.9.16
// Try to create uniqueIndex, but it does not work
Email string `gorm:"column:email; type:varchar(50); uniqueIndex:uidx_email"` / / not to take effect
Email string `gorm:"column:email; type:varchar(50); index:idx_email"`        / / to take effect

Create a unique index. Create a unique index named email
Email string `gorm:"column:email; type:varchar(50); unique"`
// Create a unique index with the custom name uidx_email
Email string `gorm:"column:email; type:varchar(50)" sql:"unique_index:uidx_email"`
Copy the code

Knowledge automatic update time

The GORM convention uses CreatedAt and UpdatedAt to track creation/update times. If such a field is defined and the default value is zero, GORM will automatically fill in the current time when it is created or updated. To use fields with different names, you can configure autoCreateTime, autoUpdateTime tags, and if you want to save UNIX (nanosecond) timestamps instead of time, simply change time. time to int. For mill. / nanosecond parameters, see the table above for an example.

// Time is automatically created and updated
type User struct { 
    // Custom fields use the timestamp to fill in nanoseconds to fill in the update time
    Updated   int64 `gorm:"autoUpdateTime:nano"` 
    // Custom fields populate the update time with timestamp milliseconds
    Updated   int64 `gorm:"autoUpdateTime:milli"` 
    // Custom fields use timestamp seconds to fill in the creation time
    Created   int64 `gorm:"autoCreateTime"` 
    If the value of the default creation time field is zero at creation time, the current time is used to fill in the field
    CreatedAt time.Time 
    // The default update time field is either zero when created or populated with the current timestamp seconds when updated
    UpdatedAt int      
}
Copy the code

Note: GORM model official documentation

Associated label

GORM association type has multiple types: BELONGS to, has One, has many, many to many Refer to the specific structure definition of the document, association mode using label options as follows:

Label options Directions for use
foreignKey Example of specifying the current model column as a join table foreign key:gorm:"foreignKey:FieldId"FieldID is the name of the foreign key field
references Specifies the column name of the reference table that will be mapped to the join table foreign key
polymorphic Specify polymorphic types, such as model names
polymorphicValue Specify polymorphic values, default table names
many2many Specifies the name of the connection table
joinForeignKey Specifies the foreign key column name of the join table that will be mapped to the current table
joinReferences Specifies the foreign key column name of the join table that will be mapped to the reference table
constraint Relational constraints such as:OnUpdate,OnDelete

Example:

// The news model
type News struct {
    Model
    Title   string   `gorm:"column:title; type:string; not null,default:''"`
    Content Content  `gorm:"foreignKey:NewsId" json:"content"` // Specify a foreign key
}
Copy the code

Note: GORM association model official documentation

The Form tag

Gin provides model binding, which binds form data to the model to facilitate parameter verification and use.

Model binding

// Form data
type LoginForm struct {
    Email     string    `form:"emial"`    
    Password  string    `form:"password"`
}
// Model or service layer model
type Email struct {
    Email       string
    Password    string
}
Copy the code

Bind form email data using form:”email”. We then get the parameter values through Bind(), ShouldBind(), and so on.

func EmailLogin (c *gin.Context) {
    var email LoginForm
    iferr := c.ShouldBind(&email); err ! =nil{... }// Get the form data bureau
    args := Email {
        Email:     email.Email,
        Password:  email.Password,
    }
    // Use the parameters later. }Copy the code

The Binding tag

Gin uses the validator.v10 package for data validation, which provides a variety of data validation methods and uses the binding:”” tag for data validation.

We add data validation tags to the above form model as follows:

type LoginForm struct {
    Email     string    `form:"emial" binding:"email"`    
    Password  string    `form:"password" binging:"required,min=6,max=10"`
}
Copy the code

Description of special symbols:

  • Comma (,) : separate multiple label options. There cannot be Spaces between commas. Otherwise, panic occurs.
  • Horizontal line (-) : The field is skipped without verification.
  • A vertical bar (|) : the use of multiple options to meet one of them.

Binding tag options:

Must check

Label options Directions for use The sample
required Indicates that the field value is mandatory and cannot be the default value binding:required
omitempty If the field is not set, it is ignored binding:reqomitemptyuired

Range checking

Range validation: slice, array and map, string, verify their length; Value, verify the size range

Label options Directions for use The sample
len The parameter value equals the specified value binding:"len=8"Equal to 8
ne Is not equal to binding:"ne=8"Is not equal to eight
max The maximum value is less than or equal to the parameter value binding:"max=8"Less than or equal to 8
min Minimum value, greater than or equal to the parameter value binding:"min=8"8 or greater
lte Parameter value Is less than or equal to the specified value binding:"lte=8"Less than or equal to 8
gte The parameter value is greater than or equal to the specified value binding:"gte=8"8 or greater
lt The parameter value is less than the specified value binding:"lt=8"Less than eight
gt The parameter value is greater than the specified value binding:"gt=8"More than 8
oneof The parameter value can be only one of the enumerated values. The value must be either a numeric value or a string separated by Spaces. If the string contains Spaces, enclose the string in single quotes binding:"oneof=red green"

Example:

type User struct {
    Name string `form:"name" binding:"required,min=1,max=10"`
    Age  unit8  `form:"age" binding:"lte=150,gte=0"`
    sex  string `form:"sex" binding:"oneof=male female"`
}
Copy the code

Note: Document address

String check

Label options Directions for use The sample
contains Parameter values contain Settings substrings binding:"contains=tom"Whether the Tom string is included
excludes Parameter values do not contain Settings substrings binding:"excludes=tom"Whether the Tom string is not included
startswith String prefix binding:"startswith=tom"Whether to start with Tom
endswith String prefix binding:"endswith=tom"Does it end with Tom

Example:

type User struct {
    Name string `form:"name" binding:"required,contains=ac,endswith=ck"`
}
Copy the code

Note: Document address

Field calibration

Label options Directions for use
eqcsfield Fields are equal across different structures, for examplestruct1 field1Whether is equal to thestruct2 field2
necsfield Fields are not equal across different structures
eqfield Equality validation for fields in the same structure, for example: enter a password twice
nefield Unequal validation of fields in the same structure
gtefield Greater than or equal to the same structure field
ltefield Less than or equal to the same structure field

Example:

// Fields are equal across different structures
type Struct1 struct { 
    Field1 string `validate:eqcsfield=Struct2.Field2` 
    Struct2 struct { 
        Field2 string}}// Verify the equality of fields in the same structure
type Email struct { 
    Email  string `validate:"lte=4"` 
    Pwd    string `validate:"min=10"` 
    Pwd2   string `validate:"eqfield=Pwd"`
}
// The same structure field validations are not equal
type User struct { 
    Name     string `validate:"lte=4"` 
    Age      int `validate:"min=20"` 
    Password string `validate:"min=10,nefield=Name"`
}
Copy the code

The other check

Label options Directions for use The sample
ip Verify valid IP addresses binding:"ip"
email Verification of valid mailbox binding:"email"
url Legitimate URL binding:"url"
uri The URI of the legal binding:"uri"
uuid Uuid validation binding:"uuid"
datetime Valid time format value verification binding:"datetime=2006-01-02"
json JSON data validation validate:"json"
numeric Numerical validation regulars:^ +] [-? [0-9] + (? : \ \. [0-9] +)? $ validate:"numeric"
number Integer validation re:^ [0-9] + $ validate:"number"
alpha Alphanumeric string validates the re:^[a-zA-Z]+$ validate:"alpha"
alphanum Alphanumeric string validation re:^[a-zA-Z0-9]+$ validate:"alphanum"
ascii Ascii character verification validate:"ascii"

Example:

type User struct { 
    Name     string  `validate:"required,min=1,max=10"` 
    Email    int     `validate:"required,email"`
    birthday string  `validate:"datetime=2006-01-02"`
    Pwd      string  `validate:"required,alphanum"`
    Score    srring  `validate:"numeric"`
}
Copy the code

Note: Document address

Refer to the article

  • GORM document
  • Golang common library: Field parameter validation library – Validator used
  • Common keywords for go-playground/validator