关于GORM的部分可以先看我之前发的这篇文章http://t.csdn.cn/3i8dw
本文中我将之前写的部分代码进行了改进,如果您觉得我改进的方式不够好或者格式不标准可以指出!因为是在自学可能有些地方不太严谨。
Gin官方文档传送门:https://gin-gonic.com/zh-cn/
目录
一、代码优化
1、项目构成部分
与上一篇文章相比多了Controller、Service、resultV0、test.http
Controller是因为之前在写springBoot项目的时候作为控制层,但是我发现由于gorm可以很好的返回数据,于是就讲原先的mapper+service融合到了一起,暂且取名为gormService吧。不知道这样做会不会出现什么问题,但是基本的流程应该是对的。
2、部分代码补充
(1)resultV0.go
package model
type ResultV0 struct {
ReturnId string `json:"returnId"`
Err error `json:"err"`
Row int64 `json:"row"`
}
创建这个结构体的原因有这样两点:
1、因为在gorm提供的方法中可以很方便的执行sql语句并返回json数据,但是像insert、update、delete这样类型的sql语句的时候,返回值是影响的行数,并不是定义的实体类。
2、在gorm官方文档中发现他的返回值可以有error类型,所以加上就可以看报错信息了。
(2)UserService.go
package gormService
import (
"Server/config"
"Server/model"
)
// 结果集
var results []model.Users
var result model.Users
// FindAll 返回所有信息
func FindAll() []model.Users {
config.DB.Find(&results)
return results
}
// FindById 返回根据主键检索(一条数据)
func FindById(index string) model.Users {
config.DB.Find(&result, index)
return result
}
// FindByName 条件查询
func FindByName(name string) []model.Users {
config.DB.Where("username LIKE ?", "%"+name+"%").Find(&results)
return results
}
// Add 新增数据
func Add(users model.Users) model.ResultV0 {
r := config.DB.Create(&users)
return model.ResultV0{ReturnId: string(users.Id), Err: r.Error, Row: r.RowsAffected}
}
// Update 根据主键修改数据
func Update(users model.Users) model.ResultV0 {
r := config.DB.Model(model.Users{}).Where("id=?", users.Id).Updates(users)
return model.ResultV0{ReturnId: string(users.Id), Row: r.RowsAffected, Err: r.Error}
}
// Delete 根据主键删除
func Delete(index string) model.ResultV0 {
r := config.DB.Delete(&model.Users{}, index)
return model.ResultV0{ReturnId: index, Row: r.RowsAffected, Err: r.Error}
}
这里的函数原先是跟实体类放在一起的,因为要使整个框架更清晰,于是把它单独拿出来放在一个包里面。并且把之前每个函数单独的sturct改为了重新定义的model.ResultV0。
(3)UserController.go
package controller
import (
"Server/gormService"
"Server/model"
"github.com/gin-gonic/gin"
)
var r = gin.Default()
func UserController() {
//FindAll 返回所有信息
r.GET("/all", func(context *gin.Context) {
result := gormService.FindAll()
if len(result) > 0 {
context.JSON(200, gin.H{
"code": 200,
"message": "success",
"data": result})
} else {
context.JSON(101, nil)
}
})
// FindById 返回根据主键检索(一条数据)
r.POST("/find", func(context *gin.Context) {
id := context.PostForm("id")
result := gormService.FindById(id)
if result.Id > 0 {
context.JSON(200, gin.H{
"code": 200,
"data": result})
} else {
context.JSON(101, nil)
}
})
// FindByName 条件查询
r.POST("/findByName", func(context *gin.Context) {
name := context.PostForm("name")
user := gormService.FindByName(name)
if len(user) > 0 {
context.JSON(200, gin.H{
"code": 200,
"data": user,
})
} else {
context.JSON(101, nil)
}
})
// Add 新增数据
r.POST("/add", func(context *gin.Context) {
var user model.Users
context.ShouldBind(&user)
result := gormService.Add(user)
if result.Err != nil {
context.JSON(101, nil)
} else {
context.JSON(200, gin.H{
"code": 200,
"data": result})
}
})
// Update 根据主键修改数据
r.POST("/update", func(context *gin.Context) {
var user model.Users
context.ShouldBind(&user)
result := gormService.Update(user)
if result.Err != nil {
context.JSON(101, nil)
} else {
context.JSON(200, result)
}
})
// Delete 根据主键删除
r.POST("/delete", func(context *gin.Context) {
index := context.PostForm("id")
result := gormService.Delete(index)
if result.Err != nil {
context.JSON(101, nil)
} else {
context.JSON(200, result)
}
})
}
func RunHttp() {
UserController()
r.Run("127.0.0.1:8080")
}
这个部分主要是构建请求和请求方式,然后接受参数来调用UserService中的函数来完成请求。这里拿一个例子分析一下
// Delete 根据主键删除
r.POST("/delete", func(context *gin.Context) {
index := context.PostForm("id")
result := gormService.Delete(index)
if result.Err != nil {
context.JSON(101, nil)
} else {
context.JSON(200, result)
}
})
根据官方文档,最开始的时候定义了
var r = gin.Default()
然后便是调动r的方法,这里主要是尝试了get和post方法。后面接一个函数,会自动补全gin.Context的参数,这个context参数很好用,但是还没有了解的很深,这里只是学了一下如何使用,后面有机会会深入看看。然后定义一个参数index用于接受参数名“id”的值。然后利用这个index调用定义的Delete方法,并且返回值赋给result,然后就是进行判断,如果错误不为空(报错)的话返回值context的返回值就是101。这个地方有点意思,之前这个地方我还定义了错误信息,放在现在你看到填为nil的部分,但是我发现将code设置成101之后,就不会有返回信息了。于是我就讲后面改为了nil。前端应该可以识别这个code:101吧。
二、接口测试
1、运行服务器
gin是通过这条语句来启动服务的,值的吐槽的他这里启动服务真的快,之前用springBoot重启一次要好半天。
r.Run("127.0.0.1:8080")
启动之后它还把接口列出来了。
2、请求测试
(1)FindAll 返回所有信息
(2) FindById 返回根据主键检索(一条数据)
(3) FindByName 条件查询
(4)Add 新增数据
(5)Update 根据主键修改数据
(6)Delete 根据主键删除
三、总结
这里在之前gorm框架完成的基础之上结合gin完成了一些简单的接口设计。主要想做的还是把从数据库到接口返回数据这一块先做通,其中肯定还有一些漏洞和不合理的地方需要修改。
gitee源码:https://gitee.com/shenyufan/go-lang
分支:3.9test