gorm官网 https://gorm.io/zh_CN/docs/update.html
1.项目结构
2.用户结构体
package model
//orm后跟表对应的字段,注意结构体字段的首字母要大写,小写不能导出
type User struct {
Id int `orm:"column:id"`
UserName string `orm:"column:user_name"`
Age int `orm:"column:age"`
Address string `orm:"column:address"`
Phone string `orm:"column:phone"`
Photo string `orm:"column:photo"`
Password string `orm:"column:password"`
Version int `orm:"column:version"`
Deleted int `orm:"column:deleted"`
CreateTime string `orm:"column:create_time"`
UpdateTime string `orm:"column:update_time"`
}
//返回对应的表
func (v User) TableName() string {
return "user"
}
3.gorm连接数据库
package data_source
import (
"awesomeProject/model"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"gopkg.in/yaml.v2"
"os"
)
var Db *sql.DB
var err error
//yml文件对应的结构体
type Config struct {
MysqlConf MysqlConf `yaml:"mysql" json:"mysql"`
}
//yml文件对应的结构体
type MysqlConf struct {
Host string `yaml:"host" json:"host"`
Port string `yaml:"port" json:"port"`
UserName string `yaml:"user_name" json:"user_name"`
Password string `yaml:"password" json:"password"`
DataBase string `yaml:"database" json:"database"`
LogoMode bool `yaml:"logo_mode" json:"logo_mode"`
}
//获取配置文件信息
func GetConfigData() Config {
file, err := os.ReadFile("config.yml")
if err != nil{
fmt.Println(err.Error())
}
var _config Config
err = yaml.Unmarshal(file, &_config)
fmt.Println(_config)
if err != nil{
fmt.Println(err.Error())
}
username := _config.MysqlConf.UserName
fmt.Println("username:" + username)
return _config
}
//连接数据库
func DbConnect() *gorm.DB{
mysql_conf := GetConfigData()
data_source := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=true&loc=Local",
mysql_conf.MysqlConf.UserName,
mysql_conf.MysqlConf.Password,
mysql_conf.MysqlConf.Host,
mysql_conf.MysqlConf.Port,
mysql_conf.MysqlConf.DataBase)
Db, err := gorm.Open("mysql", data_source)
if err != nil{
panic(err)
}
Db.LogMode(mysql_conf.MysqlConf.LogoMode)
Db.DB().SetMaxOpenConns(100)
Db.DB().SetMaxIdleConns(50)
Db.AutoMigrate(&model.User{})
return Db
}
4.配置文件
mysql:
host: localhost
port: 3306
user_name: root
password: root
database: test
logo_mode: true
5.service层配置
package service
import (
"awesomeProject/data_source"
"awesomeProject/model"
"time"
)
//获取数据库连接对象
var db = data_source.DbConnect()
//实例化一个UserService对象,方便controller调用
var UserServiceImpl = new(UserService)
//当前文件的结构体,类似java的无参构造器可以调用本页面的所有方法
type UserService struct {}
//从数据库查询所有用户信息
func (s *UserService) SelectUserList() ([]model.User, error) {
var users []model.User
//gorm查找,查找到的信息会赋值到users这个数组中
db.Find(&users)
return users, nil
}
//存储用户信息到数据库
func (s *UserService) SaveUser(user model.User) (bool, model.User){
user.CreateTime = time.Now().Format("2006-01-02 15:04:05")
user.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
//插入信息到select中的字段
res := db.Select("user_name", "age", "address", "phone", "photo", "password", "version", "deleted", "create_time", "update_time").Create(&user)
if res.Error != nil {
panic(res.Error)
}
newUser, err := s.GetUserByUserId(user.Id)
if err != nil {
panic(err)
}
return true, newUser
}
//通过id查找用户信息
func (s *UserService) GetUserByUserId(id int) (model.User, error) {
user := model.User{Id: id}
first := db.First(&user)
return user, first.Error
}
//通过id更新用户信息
func (s *UserService) UpdateUserByUserId(user model.User) (bool, model.User){
user.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
updates := db.Model(&user).Updates(model.User{
UserName: user.UserName,
Age: user.Age,
Address: user.Address,
Phone: user.Phone,
Photo: user.Photo,
Password: user.Password,
UpdateTime: user.UpdateTime,
})
if updates.Error != nil {
panic("更新错误" + updates.Error.Error())
}
newUser, err := s.GetUserByUserId(user.Id)
if err != nil {
panic(err)
}
return true, newUser
}
func (s *UserService) DeleteUserByUserId(id int) bool {
user := model.User{Id: id}
d := db.Delete(&user)
if d.Error != nil {
panic(d.Error)
return false
}
return true
}
6.controller层
package controller
import (
"awesomeProject/common/constant"
"awesomeProject/common/response"
"awesomeProject/model"
"awesomeProject/service"
"fmt"
"github.com/gin-gonic/gin"
"strconv"
)
type UserController struct {
}
// @Summary 查询用户
// @Description 查询所有用户信息
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Param object query model.User false "查询参数"
// @Success 200 object response.ResultVO 成功后返回值
// @Router /user/getList [Get]
func GetList(c *gin.Context){
list, err := service.UserServiceImpl.SelectUserList()
if err != nil {
panic(err)
}
response.Success(c, constant.SuccessCode, constant.SelectSuccessMsg, gin.H{"user": list})
}
// @Author 又菜又爱玩
// @Summary 存储用户
// @Description 存储用户信息
// @Tags 用户
// @version 1.0
// @Accept application/x-json-stream
// @Param user body model.User true "用户"
// @Success 200 object response.ResultVO 成功后返回值
// @Failure 409 object response.ResultVO 添加失败
// @Router /user/saveUser [POST]
func SaveUser(c *gin.Context) {
var user model.User
err := c.Bind(&user)
if err != nil {
c.JSON(500, gin.H{"err":err})
panic(err)
return
}
flag, id := service.UserServiceImpl.SaveUser(user)
fmt.Printf("用户的id==========================》%v\n", id)
if !flag {
response.Failure(c, constant.ErrorCode, constant.SaveErrorMsg, gin.H{"user": nil})
}
response.Success(c, constant.SuccessCode, constant.SaveSuccessMsg, gin.H{"user": id})
}
// @Author 又菜又爱玩
// @Summary 更新用户
// @Description 更新用户信息
// @Tags 用户
// @version 1.0
// @Accept application/x-json-stream
// @Param user body model.User true "用户"
// @Success 200 object response.ResultVO 成功后返回值
// @Failure 500 object response.ResultVO 添加失败
// @Router /user/UpdateUser [POST]
func UpdateByUserId(c *gin.Context) {
var user model.User
err := c.Bind(&user)
if err != nil {
c.JSON(500, gin.H{"err":err})
panic(err)
return
}
flag, id := service.UserServiceImpl.UpdateUserByUserId(user)
fmt.Printf("用户的id==========================》%v\n", id)
if !flag {
response.Failure(c, constant.ErrorCode, constant.UpDateErrorMsg, gin.H{"user": nil})
}
response.Success(c, constant.SuccessCode, constant.UpDateSuccessMsg, gin.H{"user": id})
}
// @Summary 删除用户
// @Description 通过id删除用户
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Param id path int true "删除参数"
// @Success 200 object response.ResultVO 成功后返回值
// @Router /user/delete/{id} [Delete]
func DeleteUserByUserId(c *gin.Context) {
param := c.Param("id")
atoi, err := strconv.Atoi(param)
if err != nil {
response.Failure(c, constant.ErrorCode, constant.DelErrorMsg, gin.H{"Msg": "传入参数错误"})
}
id := service.UserServiceImpl.DeleteUserByUserId(atoi)
if !id {
response.Failure(c, constant.ErrorCode, constant.DelErrorMsg, gin.H{"Msg": "删除失败"})
}
response.Success(c, constant.SuccessCode, constant.DelSuccessMsg, gin.H{"Msg": "删除成功"})
}
// @Summary 查找用户
// @Description 通过id查找用户
// @Tags 用户
// @Accept application/json
// @Produce application/json
// @Param id path int true "查找参数"
// @Success 200 object response.ResultVO 成功后返回值
// @Router /user/getUser/{id} [Get]
func GetUserByUserId(c *gin.Context) {
param := c.Param("id")
fmt.Println(param)
atoi, err := strconv.Atoi(param)
if err != nil {
response.Failure(c, constant.ErrorCode, constant.SelectErrorMsg, gin.H{"Msg": "传入参数错误"})
}
id, err := service.UserServiceImpl.GetUserByUserId(atoi)
if err != nil {
response.Failure(c, constant.ErrorCode, constant.SelectErrorMsg, gin.H{"Msg": "查找失败"})
}
response.Success(c, constant.SuccessCode, constant.SelectSuccessMsg, gin.H{"Msg": id})
}
8.主函数调用
main上的注释为gin-swagger生成接口文档的注解
package main
import (
"awesomeProject/common/router"
"github.com/gin-gonic/gin"
)
// @title 又菜又爱玩
// @version 1.0.0
// @description Gin 学习
// @termsOfService http://swagger.io/terms/
// @contact.name lzx
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host 127.0.0.1:8080
// @BasePath /api/v1
func main() {
r := gin.Default()
router.LoadUsersRouters(r)
router.LoadSwagRouters(r)
r.Run()
}
9.统一响应类
package constant
type ResponseCode int
type ResponseMsg string
const (
SuccessCode ResponseCode = 200
SelectSuccessMsg ResponseMsg = "查询成功"
SaveSuccessMsg ResponseMsg = "插入成功"
UpDateSuccessMsg ResponseMsg = "更新成功"
DelSuccessMsg ResponseMsg = "删除成功"
ErrorCode ResponseCode = 201
SelectErrorMsg ResponseMsg = "查询错误"
SaveErrorMsg ResponseMsg = "插入错误"
UpDateErrorMsg ResponseMsg = "更新错误"
DelErrorMsg ResponseMsg = "删除错误"
)
package response
import (
"awesomeProject/common/constant"
"github.com/gin-gonic/gin"
"net/http"
)
type ResultVO struct {
Code constant.ResponseCode `json:"code"`
Msg constant.ResponseMsg `json:"msg"`
Success bool `json:"success"`
Data interface{} `json:"data"`
}
/**
* 请求成功函数
*/
func Success(ctx *gin.Context, code constant.ResponseCode, msg constant.ResponseMsg, data interface{}) {
resp := &ResultVO{Code: code, Msg: msg, Success: true, Data: data}
ctx.JSON(http.StatusOK, resp)
}
/**
* 请求失败函数
*/
func Failure(ctx *gin.Context, code constant.ResponseCode, msg constant.ResponseMsg, data interface{}) {
resp := &ResultVO{Code: code, Msg: msg, Success: false, Data: data}
ctx.JSON(http.StatusInternalServerError, resp)
}
10.路由
package router
import (
"awesomeProject/controller"
"github.com/gin-gonic/gin"
)
func LoadUsersRouters(r *gin.Engine) {
users := r.Group("/user")
{
users.GET("/getList", controller.GetList)
users.POST("/saveUser", controller.SaveUser)
users.PUT("/UpdateUser", controller.UpdateByUserId)
users.DELETE("/delete/:id", controller.DeleteUserByUserId)
users.GET("/getUser/:id", controller.GetUserByUserId)
}
}