我的 API 服务器接受 post 请求,请求正文是 JSON,所以我创建了两个 struct 对象来接受 JSON 字符串并将其持久化到数据库中。但是每次我接受请求时,我都需要一遍又一遍地创建 struct 对象,我尝试清除结构而不是重新创建它。演示代码如下:
//The two struct
type Card struct {
Number string
Type string
}
type Person struct {
Name string
Cards []Card
}
var p Person
//parse JSON to the struct object
func init() {
str := `{"name":"aaa","cards":[{"number":"1","type":"visa"},{"number":"2","type":"mastercard"}]}`
json.Unmarshal([]byte(str), &p)
}
func PersistToDatabase() {
var err error
tx, err := db.Begin()
if err != nil {
return
}
defer func() {
if err != nil && tx != nil {
if err := tx.Rollback(); err != nil {
return
}
}
}
finish := make(chan bool)
stmt1, err := tx.Prepare(`insert into tb1(name) values(?)`)
if err != nil {
panic(err.Error())
}
defer stmt1.Close()
stmt2, err := tx.Prepare(`insert into tb2(name, num, type) values(?, ?, ?)`)
if err != nil {
panic(err.Error())
}
defer stmt2.Close()
go func() {
defer func() { finish <- true }()
if _, err = stmt1.Exec(p.name); err != nil {
log.Println("stmt1.Exec: ", err.Error())
return
}
for _, x := range p.Cards {
if _, err = stmt2.Exec(p.name, x.Number, x.Type); err != nil {
log.Println("stmt2.Exec: ", err.Error())
return
}
}
}
<-finish
//clear struct object
p.Name = ""
p.Cards = nil //have anything do this better?
}
在代码底部,我清除了 Name 元素,但让 Cards 元素成为了nil,我该如何做得更好?我的数据库操作有问题吗?
相关分类