当前位置:网站首页>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

边栏推荐
猜你喜欢

Équipe tensflow: Nous ne sommes pas abandonnés
![[stm32-usb-msc problem help] stm32f411ceu6 (Weact) +w25q64+usb-msc flash uses SPI2 to read out only 520kb](/img/ec/fa51b21468708609f998de1b2b84fe.jpg)
[stm32-usb-msc problem help] stm32f411ceu6 (Weact) +w25q64+usb-msc flash uses SPI2 to read out only 520kb

MySQL advanced 4

6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary

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

One revolution, two forces, three links: the "carbon reduction" roadmap behind the industrial energy efficiency improvement action plan

并发编程系列之什么是ForkJoin框架?

STM32F411 SPI2输出错误,PB15无脉冲调试记录【最后发现PB15与PB14短路】

Pico, can we save consumer VR?

做空蔚来的灰熊,以“碰瓷”中概股为生?
随机推荐
马来西亚《星报》:在WTO MC12 孙宇晨仍在坚持数字经济梦想
Rhcsa fourth day operation
HR interview: the most common interview questions and technical answers
Qt+pcl Chapter 6 point cloud registration ICP Series 2
Reading notes of top performance version 2 (V) -- file system monitoring
What is the forkjoin framework in the concurrent programming series?
Factory high-precision positioning management system, digital safety production management
Logical analysis of automatic decision of SAP CRM organization model
Survey of intrusion detection systems:techniques, datasets and challenges
[stm32-usb-msc problem help] stm32f411ceu6 (Weact) +w25q64+usb-msc flash uses SPI2 to read out only 520kb
Qt+pcl Chapter 9 point cloud reconstruction Series 2
综述 | 激光与视觉融合SLAM
S32K1xx 微控制器的硬件设计指南
TensorFlow團隊:我們沒被拋弃
自动、智能、可视!深信服SSLO方案背后的八大设计
[video memory optimization] deep learning video memory optimization method
最新NLP赛事实践总结!
Trace the source of drugs and tamp the safety dike
将ABAP On-Premises系统连接到中央检查系统以进行自定义代码迁移
她就是那个「别人家的HR」|ONES 人物