当前位置:网站首页>Use tag tag in golang structure
Use tag tag in golang structure
2022-07-27 04:05:00 【Crisp_ LF】
stay Golang Used in structures tag label
brief introduction
We can follow the field of the structure , Add some descriptions of this field ( Meta information meta), The program parses this information through reflection and uses .
Grammatical structure
// Notice that there are backquotes outside
`key:"value" key:"value"`
- In reverse quotation marks ,key No double quotes ,value quotation marks , Multiple values are separated by spaces
package main
import (
"fmt"
"reflect"
)
func main() {
type S struct {
F string `species:"gopher" color:"blue"`
}
// Instantiate structure , It is not used here , So null instantiation
s := S{
}
// Use reflection to get the type type
st := reflect.TypeOf(s)
// Get the first field
field := st.Field(0)
// Get tag What's inside
fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
}
a key :
- know tag How to write the grammatical structure of labels
Running results
blue gopher
application json code
- Through the code
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
// Generally, our field names are capitalized , But we json It's all lowercase , You can go through here tag To use lowercase to know uppercase fields
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))
}
Running results
- Generated json The format is based on json To express
{
"name": "Crisp",
"password": "123456",
"createdAt": "2022-07-21T15:59:36.200572+08:00"
}
application xml code
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 Representative attribute
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"` //> Child node
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 = " notes ."
v.Address = Address{
" Beijing ", " haidian "}
output, err := xml.MarshalIndent(v, "", " ")
if err != nil {
fmt.Printf("error:%v\n", err)
}
_, err = os.Stdout.Write(output)
if err != nil {
return
}
}
Running results
<person id="13">
<name>
<first>C</first>
<last>risp</last>
</name>
<age>18</age>
<Married>false</Married>
<City> Beijing </City>
<State> haidian </State>
<comment> notes .</comment>
</person>
application form Form binding ,gorm
- Can write multiple tag label , Use spaces to separate
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 frame form And data binding
package main
import "C"
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
//form: In the form name Usually lowercase id,json: The parameters returned to the front end by separating the front end from the front end ,binding: Field validation
User string `form:"user" json:"user" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
// binding 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": " Successfully logged in "})
} else {
c.JSON(http.StatusUnauthorized, gin.H{
"status": " unauthorized "})
}
} 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": " Successfully logged in "})
} else {
c.JSON(http.StatusUnauthorized, gin.H{
"status": " unauthorized "})
}
} else {
C.JSON(http.StatusBadRequest, gin.H{
"error": err.Error})
}
})
}
More applications
json- fromencoding/json packageUse , For details, seejson.Marshal()xml- fromencoding/xmlPackage usage , For details, seexml.Marshal()bson- fromgobsonUse , The details are inbson.Marshal(); Also bymongo-goThe driver , staybson package doctIt's detailed inprotobuf-github.com/golang/protobuf/protoUsers , The document detailsyaml- fromgopkg.in/yaml.v2Package usage , For details, seeyaml.Marshal()db- Bygithub.com/jmoiron/sqlxPackage usage ; Also bygithub.com/go-gorp/gorpPackage usageorm- fromgithub.com/astaxie/beego/ormPackage usage , SeeModels-Beego ORMgorm- Usegorm.io/gorm, Examples can be found in their documentationvalid- fromgithub.com/asaskevich/govalidatorPackage usage , Examples can be found in the project pagedatastore- fromappengine/datastore(Google App Engine platform 、Datastore service ) Use , See properties for detailsschema- be used forgithub.com/gorilla/schemafill struct HTML Form value , There are detailed instructions in the package documentasn- fromencoding/asn1Package usage , The details are inasn1.Marshal()andasn1.Unmarshal()csv- Bygithub.com/gocarina/gocsvPackage usageenv- Bygithub.com/caarlos0/envPackage usage
边栏推荐
- Do you really understand code rollback?
- 科目三: 济南章丘6号线
- 03.获取网页源代码
- VR全景制作在家装行业是谈单利器?这是为什么呢?
- C# 使用SqlSugar Updateable系统报错无效数字,如何解决?求指导!
- Plato farm brings a new experience to community users through the LAAS protocol elephant swap
- Leetcode- > 2-point search and clock in (3)
- 想要获得 Apache 官方域名邮箱吗?专访 Apache Linkis 五位新晋 Committer告诉你怎么做
- 0726~简历梳理面试总结
- 大家有遇到CDC读MySQL字段不全的情况吗?怎么处理的?
猜你喜欢

452页13万字现代智慧乡镇雪亮工程整体解决方案2022版

STM32CubeMX学习笔记(41)——ETH接口+LwIP协议栈使用(DHCP)

Program to change the priority of the process in LabVIEW

C. Cypher

《MySQL》认识MySQL与计算机基础知识

Chapter 4 决策树和随机森林

Is Jiufang intelligent investment a regular company? Talk about Jiufang intelligent investment

Share the current life -- a six week internship experience of a high school graduate in CCTV

Chapter 4 decision tree and random forest

"Gonna be right" digital collection is now on sale! Feel the spiritual resonance of artists
随机推荐
URDF_Xcaro
「Gonna Be Alright 会好的」数藏现已开售!感受艺术家的心灵共鸣
VR全景现在是不是刚需?看完你就明白了
科目三: 济南章丘6号线
分析一下CSDN大佬写的CAS,可重入锁, 非公平锁
Redis (IX) - redis distributed lock
The 100th of the commercial anti counterfeiting series - boring systems and management processes can really be thrown into the trash can - by the way, analyze a dozen useless unity game self-test proj
Golang JWT cross domain authentication
222. Number of nodes of complete binary tree
Prime factorization -- C (GCC) -- PTA
Use websocket to realize a web version of chat room (fishing is more hidden)
C语言学习笔记 —— 内存管理
3381. Mobile keyboard (Tsinghua University postgraduate entrance examination machine test question)
Golang jwt跨域鉴权
SkyWalking分布式系统应用程序性能监控工具-中
A. Round Down the Price
A. Parkway Walk
Redis(九) - Redis之分布式锁
A. Parkway Walk
科目三: 济南章丘二号线