当前位置:网站首页>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
边栏推荐
- 异常检测中的浅层模型与深度学习模型综述(A Unifying Review of Deep and Shallow Anomaly Detection)
- A unifying review of deep and shallow anomaly detection
- 摩根大通期货开户安全吗?摩根大通期货公司开户方法是什么?
- 综述 | 激光与视觉融合SLAM
- 硬件开发笔记(九): 硬件开发基本流程,制作一个USB转RS232的模块(八):创建asm1117-3.3V封装库并关联原理图元器件
- 【目标跟踪】|模板更新 时间上下文信息(UpdateNet)《Learning the Model Update for Siamese Trackers》
- 2022-07-01日报:谷歌新研究:Minerva,用语言模型解决定量推理问题
- 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
- Using swiper to make mobile phone rotation map
- 【目标跟踪】|STARK
猜你喜欢
TensorFlow團隊:我們沒被拋弃
Zhang Chi's class: several types and differences of Six Sigma data
Summary of point cloud reconstruction methods I (pcl-cgal)
The latest NLP game practice summary!
[video memory optimization] deep learning video memory optimization method
做空蔚来的灰熊,以“碰瓷”中概股为生?
[pyGame practice] do you think it's magical? Pac Man + cutting fruit combine to create a new game you haven't played! (source code attached)
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (III)
Hardware design guide for s32k1xx microcontroller
Qt+pcl Chapter 9 point cloud reconstruction Series 2
随机推荐
Pico,能否拯救消费级VR?
Qt+pcl Chapter 6 point cloud registration ICP Series 2
Zero copy technology of MySQL
Day 3 of rhcsa study
Sort out the four commonly used sorting functions in SQL
【目标跟踪】|STARK
Implementation of deploying redis sentry in k8s
软件测试的可持续发展,必须要学会敲代码?
Pocket network supports moonbeam and Moonriver RPC layers
微信小程序03-文字一左一右显示,行内块元素居中
[one day learning awk] conditions and cycles
张驰咨询:家电企业用六西格玛项目减少客户非合理退货案例
The latest NLP game practice summary!
张驰课堂:六西格玛数据的几种类型与区别
Guide de conception matérielle du microcontrôleur s32k1xx
An intrusion detection model
Overview | slam of laser and vision fusion
如何写出好代码 - 防御式编程指南
【云动向】6月上云新风向!云商店热榜揭晓
二叉树的前序,中序,后续(非递归版本)