当前位置:网站首页>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
边栏推荐
- ATSS:自动选择样本,消除Anchor based和Anchor free物体检测方法之间的差别
- 并发编程系列之什么是ForkJoin框架?
- Raytheon technology rushes to the Beijing stock exchange and plans to raise 540million yuan
- Overview | slam of laser and vision fusion
- 微服务追踪SQL(支持Isto管控下的gorm查询追踪)
- [stm32-usb-msc problem help] stm32f411ceu6 (Weact) +w25q64+usb-msc flash uses SPI2 to read out only 520kb
- One revolution, two forces, three links: the "carbon reduction" roadmap behind the industrial energy efficiency improvement action plan
- 综述 | 激光与视觉融合SLAM
- [cloud trend] new wind direction in June! Cloud store hot list announced
- 【一天学awk】条件与循环
猜你喜欢
Wechat applet 01 bottom navigation bar settings
一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图...
Don't ask me again why MySQL hasn't left the index? For these reasons, I'll tell you all
Photoshop插件-HDR(二)-脚本开发-PS插件
MySQL advanced 4
【一天学awk】条件与循环
【一天学awk】函数与自定义函数
STM32ADC模拟/数字转换详解
A unifying review of deep and shallow anomaly detection
Microservice tracking SQL (support Gorm query tracking under isto control)
随机推荐
HR面试:最常见的面试问题和技巧性答复
STM32ADC模拟/数字转换详解
如何写出好代码 - 防御式编程指南
STM32F4-TFT-SPI时序逻辑分析仪调试记录
[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)
Zhang Chi Consulting: lead lithium battery into six sigma consulting to reduce battery capacity attenuation
Zero copy technology of MySQL
Pico,能否拯救消费级VR?
【OpenCV 例程200篇】216. 绘制多段线和多边形
Implementation of deploying redis sentry in k8s
One revolution, two forces, three links: the "carbon reduction" roadmap behind the industrial energy efficiency improvement action plan
Redis seckill demo
【一天学awk】条件与循环
说明 | 华为云云商店「商品推荐榜」
ThinkPHP advanced
自动、智能、可视!深信服SSLO方案背后的八大设计
Stm32f4-tft-spi timing logic analyzer commissioning record
做空蔚来的灰熊,以“碰瓷”中概股为生?
【开源数据】基于虚拟现实场景的跨模态(磁共振、脑磁图、眼动)人类空间记忆研究开源数据集
VIM from dislike to dependence (22) -- automatic completion