go、gin、gorm、VSCode + MySQL + ApiPost 使用方法

414 阅读4分钟

1. 安装go

先下载安装go.msi文件(环境变量应该安装包完成就自动配好了,没配好自己配下),并安装vscode插件

报错:

golang环境问题——vscode中安装go插件报错、打开go文件总弹出install提示 在 VSCode 中安装 Go 插件总弹窗提示失败:

The “go-outline” command is not available. Run "go get -v github.com/ramya-rao-a/go-outline"to install …

image.png

原因:

  1. GO111MODULE未开启
  2. 未设置镜像源(代理)

解决方法:

先运行这两行代码

go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct

然后ctrl+shift+p输入Go: Install/Update Tools,全选并确定

再 install all并重启

  • GO111MODULE开启或关闭模块支持

    • GO111MODULE=off 关闭模块支持,go 会从 GOPATH 和 vendor 文件夹寻找包。
    • GO111MODULE=on 开启模块支持,go 会忽略 GOPATH 和 vendor 文件夹,只根据 go.mod 下载依赖。
    • GO111MODULE=auto 默认,在 $GOPATH/src 外面且根目录有 go.mod 文件时,开启模块支持。
  • 运行运行go envGOPROXY已变

测试运行

新建go.mod模块 go mod init my-project

新建.go文件

package main

import "fmt"

func main() {
	fmt.Println("Hello, Ljm")
}

运行.go文件go run .go

PS:推荐一篇博客 -->《 go.mod报错:缺少依赖关系_请检查代码依赖或者mod.go是否错误

2. 安装gin

看文档

报错:

下载并安装 gin:go get -u github.com/gin-gonic/gin报错

go: go.mod file not found in current directory or any parent directory.
        'go get' is no longer supported outside a module.
        To build and install a command, use 'go install' with a version,
        like 'go install example.com/cmd@latest'
        For more information, see https://golang.org/doc/go-get-install-deprecation
        or run 'go help get' or 'go help install'.

原因:

go v1.16以上go get被弃用 《go v1.16

解决方法:

go get golang.org/x/tools/cmd/goimports
go get -u github.com/gin-gonic/gin

这时就会出现 .mod 和 .sum文件

测试运行

新建一个.go项目

package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}

运行go run .go

浏览器中访问https://localhost:8080/ping,会返回一个json数据格式的pong消息

安装gorm

看文档

go get -u gorm.io/gorm 
go get -u gorm.io/driver/sqlite 

链接MySQL数据库

gorm文档:Mysql,连接池,迁移

  1. 链接数据库
package main

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func main() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:123456@tcp(127.0.0.1:3306)/crud-list?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	fmt.Println(db)
	fmt.Println(err)

	// 连接池
	sqlDB, err := db.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(10 * time.Second) // 10秒

	// 结构体(写入数据)
	type List struct {
		Name    string
		State   string
		Phone   string
		Email   string
		Address string
	}

	// 迁移
	db.AutoMigrate(&List{})

	// 接口
	r := gin.Default()

	// 端口号
	PORT := "3001"
	r.Run(":" + PORT)

}
  1. 解决此时主键缺失及表名复数的问题 主键缺失:gorm.Model添加到结构体

表名复数:GORM 配置

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
	NamingStrategy: schema.NamingStrategy{
		SingularTable: true, // 表名变回单数
	},
})
  1. 结构体定义和优化
type List struct {
	gorm.Model
	Name    string `gorm: "type:varchar(20); not null" json:"name" binding:"required"`
	State   string `gorm: "type:varchar(20); not null" json:"state" binding:"required"`
	Phone   string `gorm: "type:varchar(20); not null" json:"phone" binding:"required"`
	Email   string `gorm: "type:varchar(40); not null" json:"email" binding:"required"`
	Address string `gorm: "type:varchar(200); not null" json:"address" binding:"required"`
}

实现CRUD功能(ApiPost调试)

0. get测试接口

看gin文档,运行以后在ApiPost先新建项目,再新建GET请求,端口号为127.0.0.1:3001,点发送,出现如下响应即成功

r.GET("/", func(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "请求成功",
	})
})

1. post增加接口

gin:模型绑定和验证;gorm:CRUD接口-创建

r.POST("/user/add", func(c *gin.Context) {
	var data List

	err := c.ShouldBindJSON(&data)

	// 判断绑定是否有错
	if err != nil {
		c.JSON(200, gin.H{
			"msg":  "添加失败",
			"data": gin.H{},
			"code": 400,
		})
	} else {

		// 数据库操作
		db.Create(&data) // 创建一条数据

		c.JSON(200, gin.H{
			"msg":  "添加成功",
			"data": data,
			"code": 200,
		})
	}
})

运行后在apipost新建post接口,输入完整路径,body里写

{
    "name" : "张三",
    "state" : "在职",
    "phone" : "13467979888",
    "email" : "123456@qq.com",
    "address" : "广东省 深圳市 龙华区"
}

点发送后检查数据库发现数据上传了

2. delete删除接口

r.DELETE("/user/delete/:id", func(c *gin.Context) {
		var data []List

		// 接受 id
		id := c.Param("id")

		// 查找 id
		db.Where("id = ?", id).Find(&data)

		// 存在删,不存在报错
		if len(data) == 0 {
			c.JSON(200, gin.H{
				"msg":  "id没有找到,删除失败",
				"code": 400,
			})
		} else {
			// 操作数据库删除
			db.Where("id = ?", id).Delete(&data)

			c.JSON(200, gin.H{
				"msg":  "删除成功",
				"code": 200,
			})
		}
	})

3. put修改接口

4. get条件查询接口

5. get请求全部数据和分页数据

apipost新建get请求,设置query参数

uTools_1683602627621.png

常见报错:

  1. 请求为404?看看是不是路径没写全!

源代码:

基于go,gin,gorm的一个实现了基本CRUD管理系统的测试项目 (github.com)