【Gin】(六)Gin 多路由+控制器+公共返回Json+mysql的CURD

一、环境安装

1、GO语言环境安装

【Golang】(二)Go语言环境安装_安装golang 环境-CSDN博客

 

2、Gin 介绍与环境搭建

【Gin】(一)Gin 介绍与环境搭建-CSDN博客

 

二、代码结构

82c65fe84d03446b869ba0d7b3fef12f.png

 

三、代码实现

1、数据库建表语句

CREATE TABLE `users` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
 `username` varchar(255) NOT NULL COMMENT '用户名',
 `password` varchar(255) NOT NULL COMMENT '密码',
 `status` enum('active','inactive','deleted') NOT NULL DEFAULT 'active' COMMENT '用户状态',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

insert into users(username, password) values ('test1', 'test1'),('test2', 'test2'),('test3', 'test3')

 

2、配置文件

comfig/Db.go

package config

const (
	MYSQL_DB = "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
)

 

3、model层

model/UserModel.go

package model

type UserModel struct {
	Id       int64  `json:"id" gorm:"primary_key"`
	Username string `json:"username"`
	Password string `json:"password"`
}

func (UserModel) TableName() string {
	return "users"
}

 

4、dao层

dao/UserDao.go

package dao

import (
	"gin01/common"
	"gin01/model"
)

func GetUserInfo(id int) (model.UserModel, error) {
	var user model.UserModel
	err := common.Db.Where("id = ?", id).First(&user).Error
	return user, err
}

func GetUserList() ([]model.UserModel, error) {
	var userList []model.UserModel
	err := common.Db.Find(&userList).Error
	return userList, err
}

func AddUser(user model.UserModel) error {
	err := common.Db.Create(&user).Error
	return err
}

func ModifyUser(id int, username string) error {
	err := common.Db.Model(&model.UserModel{}).Where("id = ?", id).Update("username", username).Error
	return err
}

func DeleteUser(id int) error {
	err := common.Db.Where("id = ?", id).Delete(&model.UserModel{}).Error
	return err
}

 

5、controller层

controller/UserController.go

package controller

import (
	"gin01/common"
	"gin01/dao"
	"gin01/model"
	"gin01/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type UserController struct{}

/*
*
获取用户列表
*/
func (u UserController) GetUserList(c *gin.Context) {
	userList, err := dao.GetUserList()
	if err != nil {
		common.RetError(c, http.StatusInternalServerError, err.Error())
		return
	} else {
		common.RetSuccess(c, http.StatusOK, "success", userList, 1)
	}

}

/*
*
获取用户信息
*/
func (u UserController) GetUserInfo(c *gin.Context) {
	idStr := c.Param("id")

	id, _ := strconv.Atoi(idStr)
	user, err := dao.GetUserInfo(id)
	if err != nil {
		common.RetError(c, http.StatusInternalServerError, err.Error())
	} else {
		common.RetSuccess(c, http.StatusOK, "success", user, 1)
	}

}

/*
*
新增用户信息
*/
func (u UserController) AddUser(c *gin.Context) {
	username := c.DefaultPostForm("user_name", "")
	userpass := c.DefaultPostForm("user_pass", "")

	if username == "" || userpass == "" {
		common.RetError(c, http.StatusInternalServerError, "用户名或密码不能为空")
		return
	}

	userpass = util.GenMd5(userpass)
	user := model.UserModel{Username: username, Password: userpass}
	err := dao.AddUser(user)
	if err != nil {
		common.RetError(c, http.StatusInternalServerError, err.Error())
	} else {
		common.RetSuccess(c, http.StatusOK, "success", user.Id, 1)
	}

}

/*
*
更新用户信息
*/
func (u UserController) ModifyUser(c *gin.Context) {
	idStr := c.Param("id")
	if idStr == "" {
		common.RetError(c, http.StatusInternalServerError, "用户不存在1")
		return
	}

	id, _ := strconv.Atoi(idStr)
	user, _ := dao.GetUserInfo(id)
	if user == (model.UserModel{}) {
		common.RetError(c, http.StatusInternalServerError, "用户不存在2")
		return
	}

	nameStr := c.DefaultPostForm("user_name", "")

	err := dao.ModifyUser(id, nameStr)
	if err != nil {
		common.RetError(c, http.StatusInternalServerError, err.Error())
	} else {
		common.RetSuccess(c, http.StatusOK, "success", user.Id, 1)
	}
}

/*
*
删除用户
*/
func (u UserController) DeleteUser(c *gin.Context) {
	idStr := c.Param("id")
	if idStr == "" {
		common.RetError(c, http.StatusInternalServerError, "用户不存在1")
		return
	}

	id, _ := strconv.Atoi(idStr)
	user, _ := dao.GetUserInfo(id)
	if user == (model.UserModel{}) {
		common.RetError(c, http.StatusInternalServerError, "用户不存在2")
		return
	}

	err := dao.DeleteUser(id)
	if err != nil {
		common.RetError(c, http.StatusInternalServerError, err.Error())
	} else {
		common.RetSuccess(c, http.StatusOK, "success", id, 1)
	}
}

func (u UserController) GetUserErr(c *gin.Context) {
	common.RetError(c, http.StatusInternalServerError, "error")
}

 

controller/NewsController.go

package controller

import (
	"gin01/common"
	"github.com/gin-gonic/gin"
	"net/http"
)

type NewsController struct{}

func (u NewsController) GetNewsList(c *gin.Context) {
	common.RetSuccess(c, http.StatusOK, "success", "news list", 1)
}

func (u NewsController) GetNewsInfo2(c *gin.Context) {
	cid := c.DefaultPostForm("cid", "100")
	name := c.DefaultPostForm("name", "a100")
	common.RetSuccess(c, http.StatusOK, "success", "news info,cid:"+cid+",name:"+name, 1)
}

func (u NewsController) GetNewsInfo(c *gin.Context) {
	param := make(map[string]interface{})
	err := c.BindJSON(&param)
	if err == nil {
		cid := param["cid"].(string)
		name := param["name"].(string)
		common.RetSuccess(c, http.StatusOK, "success", "news info,cid:"+cid+",name:"+name, 1)
		return
	}
	common.RetError(c, http.StatusInternalServerError, "error")
}

func (u NewsController) GetNewsErr(c *gin.Context) {
	common.RetError(c, http.StatusInternalServerError, "error")
}

 

6、公共方法

common/DbInit.go

package common

import (
	"fmt"
	"gin01/config"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"time"
)

var (
	Db  = &gorm.DB{}
	err error
)

func init() {
	Db, err = gorm.Open("mysql", config.MYSQL_DB)
	if err != nil {
		fmt.Print("db connect error")
	}

	if Db.Error != nil {
		fmt.Print("db database error")
	}

	Db.DB().SetMaxIdleConns(10)
	Db.DB().SetMaxOpenConns(100)
	Db.DB().SetConnMaxLifetime(time.Hour)
}

 

common/R.go

package common

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type JsonStruct struct {
	Code  int         `json:"code"`
	Msg   interface{} `json:"msg"`
	Data  interface{} `json:"data"`
	Count int64       `json:"count"`
}

type JsonErrStruct struct {
	Code int         `json:"code"`
	Msg  interface{} `json:"msg"`
}

func RetSuccess(c *gin.Context, code int, msg interface{}, data interface{}, count int64) {
	json := &JsonStruct{
		code,
		msg,
		data,
		count,
	}
	c.JSON(http.StatusOK, json)
}

func RetError(c *gin.Context, code int, msg interface{}) {
	json := &JsonErrStruct{
		Code: code,
		Msg:  msg,
	}
	c.JSON(http.StatusOK, json)
}

 

7、工具方法

util/StrUtil.go

package util

import (
	"crypto/md5"
	"encoding/hex"
)

// GenMd5 计算md5值
func GenMd5(s string) string {
	m := md5.Sum([]byte(s))
	return hex.EncodeToString(m[:])
}

 

8、路由层router

router/User.go

package router

import (
	"gin01/controller"
	"github.com/gin-gonic/gin"
)

func RouterUser(r *gin.Engine) {

	user := r.Group("/user")
	{

		// 用户列表
		user.GET("/list", controller.UserController{}.GetUserList)

		// 用户信息
		user.GET("/info/:id/", controller.UserController{}.GetUserInfo)

		// 用户新增
		user.POST("/add", controller.UserController{}.AddUser)

		// 用户删除
		user.DELETE("/del/:id", controller.UserController{}.DeleteUser)

		// 用户更新
		user.PUT("/modify/:id", controller.UserController{}.ModifyUser)

		// 错误
		user.GET("/err", controller.UserController{}.GetUserErr)
	}

}

 

router/News.go

package router

import (
	"gin01/controller"
	"github.com/gin-gonic/gin"
)

func RouterNews(r *gin.Engine) {

	news := r.Group("/news")
	{
		news.GET("/list", controller.NewsController{}.GetNewsList)
		news.POST("/info", controller.NewsController{}.GetNewsInfo)
	}

}

 

9、入口文件main

main.go

package main

import (
	"gin01/router"
	"github.com/gin-gonic/gin"
)

func main() {
	// 创建服务
	server := gin.Default()

	// 路由设置
	router.RouterUser(server)
	router.RouterNews(server)

	// 启动服务
	server.Run(":8080")
}

 

四、测试

1、新增用户

curl --location '127.0.0.1:8080/user/add' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'user_name=张三' \
--data-urlencode 'user_pass=密码'

e158701d00294237917c9f4491ffc733.png

 

2、用户列表

curl --location '127.0.0.1:8080/user/list'

1cc6850665af40d8b2a068ff497170e2.png

 

3、修改用户

curl --location --request PUT '127.0.0.1:8080/user/modify/7' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'user_name=占三'

00f4fd93f1dc4853a998763b4cc5cdab.png

 

4、删除用户

curl --location --request DELETE '127.0.0.1:8080/user/del/7' \
--data ''

68803bc6e8c3412f8b6e792aeab82e11.png

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

forest_long

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值