首先往数据库插入数据,就需要连接数据库(笔者此处使用的是PostgreSQL)
因此在项目中引入如下依赖(这两个依赖版本号不一致,可能会出现异常)
gorm.io/driver/postgres // 依赖是用于连接和操作 PostgreSQL 数据库
gorm.io/gorm // 对象关系映射 (ORM) 库,简化 Golang 程序与数据库的交互
引入依赖
require (
github.com/gin-gonic/gin v1.9.1
gorm.io/driver/postgres v1.2.3
gorm.io/gorm v1.22.3
)
创建web应用,并定义接口
type User struct {
ID uint `gorm:"primaryKey"`
Mobile string
Password string
Firstname string
Lastname string
Role string
CreateTime time.Time `gorm:"column:create_time"`
UpdateTime time.Time `gorm:"column:update_time"`
}
type ResponseData struct {
Code string `json:"code"`
Message string `json:"message"`
}
func main() {
// 创建Gin的实例
r := gin.Default()
// 定义路由处理程序
r.GET("/ok", okHandler)
r.POST("/insert", insertHandler)
// 启动Gin服务
if err := r.Run(":8080"); err != nil {
// 处理启动服务时的错误
fmt.Println("启动Gin服务失败:", err)
}
}
func insertHandler(c *gin.Context) {
// 连接数据库
db, err := connectToDatabase()
if err != nil {
responseData := ResponseData{
Code: "500",
Message: "连接失败",
}
c.JSON(500, responseData)
return
}
// 从请求体中解析 JSON 数据到 User 结构体
var newUser User
if err := c.ShouldBindJSON(&newUser); err != nil {
responseData := ResponseData{
Code: "400",
Message: "请求体格式错误",
}
c.JSON(400, responseData)
return
}
newUser.CreateTime = time.Now()
newUser.UpdateTime = time.Now()
err = insertDataToDatabase(db, newUser)
if err != nil {
responseData := ResponseData{
Code: "500",
Message: "插入失败",
}
c.JSON(500, responseData)
return
}
responseData := ResponseData{
Code: "200",
Message: "success",
}
c.JSON(200, responseData)
}
func connectToDatabase() (*gorm.DB, error) {
dsn := "host=ipAddr user=postgres password=postgres dbname=test port=5432 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
return db, nil
}
func insertDataToDatabase(db *gorm.DB, user User) error {
if err := db.Table("_user").Create(&user).Error; err != nil {
return err
}
return nil
}
测试
curl -X POST -H "Content-Type: application/json" -d '{
"mobile": "152222111x",
"password": "password",
"firstname": "Alex",
"lastname": "Danne",
"role": "USER"
}' http://localhost:8080/insert
在PostgreSQL数据库查看到对应记录,成功!
标签:responseData,return,err,nil,数据库,插入,Gin,gorm,string From: https://www.cnblogs.com/ashet/p/17978339