当前位置:网站首页>Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)
Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)
2022-07-01 15:45:00 【Swordsman a Liang_ ALiang】
Catalog
Query all interfaces that have not been logically deleted
according to ID Delete interface
Time field serialization problem processing
Learning notes , Where is where .
Next to the previous article :Go English learning notes - gorm Use - Database configuration 、 Table new | Web frame Gin( 7、 ... and )_ Swordsman a Liang _ALiang The blog of -CSDN Blog
The database initialization configuration has been completed , In the last article, I wrote a simple demo Interface .
This article follows the previous one , Add, delete, modify and check the table , At the same time, the time field is specially processed .
Project address :github Address
Add / modify interface
Generally, we are in actual projects , It will merge the new interface with the update and modification interface , That is, pass parameters with ID If yes, it is modified , No ID If yes, it is new .
According to the compilation method of the project structure , stay student_service Add below AddOrUpdateStudent Method .
The method code is as follows :
// Add or update students
func (t StudentImpl) AddOrUpdateStudent(student *db_entity.Student) rsp.ResponseMsg {
log.Logger.Info(" Add or update student parameters :", log.Any("Student", student))
_db := mysql.GetDB()
if student.Id != 0 {
_db.Model(&student).Updates(student)
} else {
_db.Create(&student)
}
return *rsp.SuccessMsg(" Successful operation ")
}Be careful : In the interface test, you will find that delivery update_time Time field parsing error , In the following summary, we will talk about customizing the event structure to solve json Time field serialization problem .
Query all interfaces that have not been logically deleted
stay student_service Add below SelectAll Method , Yes del_flag by 0 Query by users .
The method code is as follows :
// Query all students
func (t StudentImpl) SelectAll() rsp.ResponseMsg {
log.Logger.Info(" Query all students ")
_db := mysql.GetDB()
var _result []db_entity.Student
_db.Where("del_flag = ?", 0).Find(&_result)
return *rsp.SuccessMsg(_result)
}according to ID Delete interface
stay student_service Add new basis ID Delete data interface .
The method code is as follows :
// according to id Delete students
func (t StudentImpl) DeleteById(id int32) rsp.ResponseMsg {
log.Logger.Info(" according to id Delete students ")
_db := mysql.GetDB()
_db.Delete(&db_entity.Student{}, id)
return *rsp.SuccessMsg(" Delete successful ")
}Time field serialization problem processing
because json Can't serialize directly time.Time type , There are many solutions online , I mainly use the method of rewriting the serialization method of user-defined time types to solve .
stay constants Under the table of contents , establish common.go file .
common.go The code is as follows :
package constants
import (
"database/sql/driver"
"fmt"
"time"
)
type HTime struct {
time.Time
}
var (
formatTime = "2006-01-02 15:04:05"
)
func (t HTime) MarshalJSON() ([]byte, error) {
formatted := fmt.Sprintf("\"%s\"", t.Format(formatTime))
return []byte(formatted), nil
}
func (t *HTime) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+formatTime+`"`, string(data), time.Local)
*t = HTime{Time: now}
return
}
func (t HTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
func (t *HTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = HTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
Be careful :
1、 Redefinition HTime Structure , Adjust the serialization method .
2、Student In the structure UpdateTime Adjust the field data type to HTime, Adjusted as follows .
type Student struct {
Id int32 `json:"id" gorm:"column:id;primary_key;AUTO_INCREMENT;comment:'id'"`
Name string `json:"name" gorm:"column:name;type:varchar(255);comment:' name '"`
Age int64 `json:"age" gorm:"column:age;comment:' Age '"`
Content string `json:"content" gorm:"column:content;type:varchar(255);comment:' describe '"`
UpdateTime constants.HTime `json:"update_time" time_format:"unix" gorm:"column:update_time"`
DelFlag int64 `json:"del_flag" gorm:"column:del_flag;comment:' Delete logo '"`
}Interface validation
controller Add interface code in layer , as follows :
// Add or modify a student information
func (s StudentController) AddOrUpdateStudent(context *gin.Context) {
var addOrUpdateStudent db_entity.Student
log.Logger.Info("AddOrUpdateStudent Interface ")
if err := context.ShouldBindJSON(&addOrUpdateStudent); err != nil {
log.Logger.Panic(" Parameter exception ")
}
if _, err := json.Marshal(addOrUpdateStudent); err != nil {
log.Logger.Panic(" Parameter parsing exception ")
}
_rsp := services.StudentServ.AddOrUpdateStudent(&addOrUpdateStudent)
context.JSON(http.StatusOK, _rsp)
}
// Query all students
func (s StudentController) SelectAll(context *gin.Context) {
log.Logger.Info("SelectAll Interface ")
_rsp := services.StudentServ.SelectAll()
context.JSON(http.StatusOK, _rsp)
}
// according to id Delete students
func (s StudentController) DeleteById(context *gin.Context) {
log.Logger.Info("DeleteById Interface ")
_id := context.Query("id")
_a, _ := strconv.ParseInt(_id, 10, 64)
_rsp := services.StudentServ.DeleteById(int32(_a))
context.JSON(http.StatusOK, _rsp)
}router Add routing path , as follows :
func StudentRouter(r *gin.Engine) {
r.POST("/student/addOne", controllers.StudentCtrl.StudentAddOne)
r.POST("/student/addOrUpdateStudent", controllers.StudentCtrl.AddOrUpdateStudent)
r.GET("/student/selectAll", controllers.StudentCtrl.SelectAll)
r.DELETE("/student/deleteById", controllers.StudentCtrl.DeleteById)
}
Verify them separately 3 Interface .
Add / modify interface

![]()
Query interface

Delete interface


Summary
To be honest, I'm a little busy recently , Take time to study when you are busy . Continue to operate some complex query operations later .
Reference link :gorm time.Time Use hook function to solve deserialization problem _qq_26372385 The blog of -CSDN Blog

边栏推荐
猜你喜欢

Deep operator overloading (2)
![[target tracking] |stark](/img/e2/83e9d97cfb8c49cfb8d912cfe2f858.png)
[target tracking] |stark

Hardware development notes (9): basic process of hardware development, making a USB to RS232 module (8): create asm1117-3.3v package library and associate principle graphic devices
![[200 opencv routines] 216 Draw polylines and polygons](/img/47/3e5564ff9cf5fa3ef98a2ea27694cf.png)
[200 opencv routines] 216 Draw polylines and polygons

What is the forkjoin framework in the concurrent programming series?

【显存优化】深度学习显存优化方法

Hardware design guide for s32k1xx microcontroller

【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(三)
![[video memory optimization] deep learning video memory optimization method](/img/87/795429126aef284d55d2217f393ecb.png)
[video memory optimization] deep learning video memory optimization method

Crypto Daily:孙宇晨在MC12上倡议用数字化技术解决全球问题
随机推荐
如何写出好代码 - 防御式编程指南
大龄测试/开发程序员该何去何从?是否会被时代抛弃?
Automatique, intelligent, visuel! Forte conviction des huit conceptions derrière la solution sslo
For the sustainable development of software testing, we must learn to knock code?
ATSs: automatically select samples to eliminate the difference between anchor based and anchor free object detection methods
软件测试的可持续发展,必须要学会敲代码?
Recommendation of data acquisition tools and detailed graphic process of data acquisition list
Pocket network supports moonbeam and Moonriver RPC layers
【一天学awk】条件与循环
求求你们,别再刷 Star 了!这跟“爱国”没关系!
Hardware design guide for s32k1xx microcontroller
Phpcms background upload picture button cannot be clicked
Photoshop插件-HDR(二)-脚本开发-PS插件
【Pygame实战】你说神奇不神奇?吃豆人+切水果结合出一款你没玩过的新游戏!(附源码)
Overview | slam of laser and vision fusion
使用swiper制作手机端轮播图
雷神科技冲刺北交所,拟募集资金5.4亿元
One revolution, two forces, three links: the "carbon reduction" roadmap behind the industrial energy efficiency improvement action plan
AVL 平衡二叉搜索树
Sort out the four commonly used sorting functions in SQL