当前位置:网站首页>在Golang结构体中使用tag标签
在Golang结构体中使用tag标签
2022-07-27 02:37:00 【Crisp_LF】
在Golang结构体中使用tag标签
简介
我们可以在结构体的字段后面,添加一些对该字段的说明(元信息meta),程序通过反射解析这些信息并使用。
语法结构
//注意外边是反引号
`key:"value" key:"value"`
- 反引号括起来,key不加双引号,value加双引号,多个值中间用空格分开
package main
import (
"fmt"
"reflect"
)
func main() {
type S struct {
F string `species:"gopher" color:"blue"`
}
//实例化结构体,在这里没有使用到,所以空实例化
s := S{
}
//使用反射获得结构体的type类型
st := reflect.TypeOf(s)
//拿到第一个字段
field := st.Field(0)
//拿到tag里面的东西
fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
}
重点:
- 知道tag标签的语法结构是怎么写的
运行结果
blue gopher
应用json编码
- 通过代码进行阐述
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
//一般我们字段名都是大写的,但是我们json里面都是小写的,这里就可以通过tag来使用小写来知道大写的字段
type User struct {
Name string `json:"name"`
Password string `json:"password"`
CreatedAt time.Time `json:"createdAt"`
}
func main() {
u := &User{
Name: "Crisp",
Password: "123456",
CreatedAt: time.Now(),
}
out, err := json.MarshalIndent(u, "", " ")
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println(string(out))
}
运行结果
- 生成的json格式就是按照字段名后面的json说明来表示的
{
"name": "Crisp",
"password": "123456",
"createdAt": "2022-07-21T15:59:36.200572+08:00"
}
应用xml编码
package main
import (
"encoding/xml"
"fmt"
"os"
)
func main() {
type Address struct {
City, State string
}
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"` //attr代表属性
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"` //>代表子节点
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:"comment"`
}
v := &Person{
Id: 13, FirstName: "C", LastName: "risp", Age: 18}
v.Comment = "注释."
v.Address = Address{
"北京", "海淀"}
output, err := xml.MarshalIndent(v, "", " ")
if err != nil {
fmt.Printf("error:%v\n", err)
}
_, err = os.Stdout.Write(output)
if err != nil {
return
}
}
运行结果
<person id="13">
<name>
<first>C</first>
<last>risp</last>
</name>
<age>18</age>
<Married>false</Married>
<City>北京</City>
<State>海淀</State>
<comment>注释.</comment>
</person>
应用form表单绑定,gorm
- 可以写多个tag标签,使用空格分开
type Channel struct {
Id uint64 `form:"id" gorm:"primaryKey"`
Title string `form:"title" gorm:"title"`
Slug string `form:"slug" gorm:"slug"`
Content string `form:"content" gorm:"content"`
Status int `form:"status" gorm:"status"`
Weight int `form:"weight" gorm:"weight"`
}
gin框架form和数据绑定
package main
import "C"
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
//form:表单中的name一般是小写的id,json:前后端分离返回给前端的参数,binding:字段校验
User string `form:"user" json:"user" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
// 绑定 JSON ({"user":"manu","password":"123"})
router.POST("/loginJSON", func(c *gin.Context) {
var json Login
if err := c.ShouldBindJSON(&json); err == nil {
if json.User == "manu" && json.Password == "123" {
c.JSON(http.StatusOK, gin.H{
"status": "成功登录"})
} else {
c.JSON(http.StatusUnauthorized, gin.H{
"status": "未授权"})
}
} else {
C.JSON(http.StatusBadRequest, gin.H{
"error": err.Error()})
}
})
//HTML form (user=manu&password=123)
router.POST("/loginForm", func(c *gin.Context) {
var form Login
if err := c.ShouldBind(&form); err == nil {
if form.User == "manu" && form.Password == "123" {
c.JSON(http.StatusOK, gin.H{
"status": "成功登录"})
} else {
c.JSON(http.StatusUnauthorized, gin.H{
"status": "未授权"})
}
} else {
C.JSON(http.StatusBadRequest, gin.H{
"error": err.Error})
}
})
}
更多应用
json-由encoding/json包使用,详细信息见json.Marshal()xml-由encoding/xml包使用,详细信息见xml.Marshal()bson-由gobson使用,详细信息在bson.Marshal();也由mongo-go驱动程序,在bson package doct中有详细说明protobuf-github.com/golang/protobuf/proto使用者,文档中有详细说明yaml-由gopkg.in/yaml.v2包使用,详细信息见yaml.Marshal()db-被github.com/jmoiron/sqlx包使用;也被github.com/go-gorp/gorp包使用orm-由github.com/astaxie/beego/orm包使用,详见Models-Beego ORMgorm-使用gorm.io/gorm,示例可以在他们的文档中找到valid-由github.com/asaskevich/govalidator包使用,示例可以在项目页面中找到datastore-由appengine/datastore(Google App Engine平台、Datastore服务)使用,详情见属性schema-用于github.com/gorilla/schema填充struct HTML表单值,在包文档中有详细说明asn-由encoding/asn1包使用,详细信息在asn1.Marshal()和asn1.Unmarshal()csv-被github.com/gocarina/gocsv包使用env-被github.com/caarlos0/env包使用
边栏推荐
- C# 使用SqlSugar Updateable系统报错无效数字,如何解决?求指导!
- Installation and use of anti-virus software ClamAV
- A. YES or YES?
- Chapter 5 decision tree and random forest practice
- Process analysis of object creation
- 真正意义上的数字零售应当具有更加丰富的内涵和意义
- 面试题:String类中三种实例化对象的区别
- Is it safe for tongdaxin to open an account
- Characteristics and determination scheme of Worthington pectinase
- Alibaba cloud server domain name and port web page cannot access the problem record
猜你喜欢

分享当下人生——一个高中毕业生在中央电视台的六星期实习经历

【安卓小叙】Kotlin多线程编程(一)

科目三: 济南章丘6号线

Characteristics and experimental suggestions of abbkine abfluor 488 cell apoptosis detection kit

Chapter 4 decision tree and random forest

Meta Quest内容生态总监谈App Lab设计初衷

On the first day of Shenzhen furniture exhibition, the three highlights of Jin Ke'er booth were unlocked!

jmeter接口测试(登录、注册)

Characteristics and determination scheme of Worthington pectinase

Kettle读取按行分割的文件
随机推荐
Chapter 5 decision tree and random forest practice
[Yugong series] July 2022 go teaching course 018 switch of branch structure
明汯投资裘慧明:长期优异超额的背后考验的是团队的投研能力和策略的完整性
【无标题】
SkyWalking分布式系统应用程序性能监控工具-中
Debug mode in pycharm for detailed debugging
LeetCode 第二十八天
Daffodils (day 78)
C语言力扣第43题之字符串相乘。优化竖式
Using redis C library, the problem of asynchronous memory leakage
C#怎么实现给Word每一页设置不同文字水印
Director of meta quest content ecology talks about the original intention of APP lab design
Number of square arrays (day 81)
Implementation of API short message gateway based on golang
Leetcode- > 2-point search and clock in (3)
回归测试:意义、挑战、最佳实践和工具
"Date: write error: no space left on device" solution
九方智投是正规公司吗?一起聊聊九方智投
mysql中case when返回多个字段处理方案
DTS is equipped with a new self-developed kernel, which breaks through the key technology of the three center architecture of the two places Tencent cloud database