给我生成一段gin gorm 的web项目
时间: 2023-05-19 14:02:48 浏览: 111
基于GIN + GORM + WIRE实现的web脚手架,支持gorm数据库操作、cors 跨域、集成jwt鉴权等.zip
好的,以下是一段基于gin和gorm的web项目的代码示例:
```go
package main
import (
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"not null"`
Age int `gorm:"not null"`
}
func main() {
dsn := "user:password@tcp(127.0.0.1:3306)/db_name?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Auto Migrate
db.AutoMigrate(&User{})
r := gin.Default()
// Get all users
r.GET("/users", func(c *gin.Context) {
var users []User
db.Find(&users)
c.JSON(200, users)
})
// Create a user
r.POST("/users", func(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
db.Create(&user)
c.JSON(200, user)
})
// Get a user by ID
r.GET("/users/:id", func(c *gin.Context) {
var user User
if err := db.First(&user, c.Param("id")).Error; err != nil {
c.JSON(404, gin.H{"error": "User not found"})
return
}
c.JSON(200, user)
})
// Update a user by ID
r.PUT("/users/:id", func(c *gin.Context) {
var user User
if err := db.First(&user, c.Param("id")).Error; err != nil {
c.JSON(404, gin.H{"error": "User not found"})
return
}
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
db.Save(&user)
c.JSON(200, user)
})
// Delete a user by ID
r.DELETE("/users/:id", func(c *gin.Context) {
var user User
if err := db.First(&user, c.Param("id")).Error; err != nil {
c.JSON(404, gin.H{"error": "User not found"})
return
}
db.Delete(&user)
c.JSON(200, gin.H{"message": "User deleted"})
})
r.Run(":8080")
}
```
这段代码实现了一个简单的用户管理系统,可以通过HTTP接口进行用户的增删改查操作。其中使用了gin作为HTTP框架,gorm作为ORM框架,MySQL作为数据库。
阅读全文