用gin+ent框架 写一个对user用户的增删改查
时间: 2024-04-06 10:31:04 浏览: 199
好的,我可以为您提供一个简单的示例代码:
```
package main
import (
"context"
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/dialect/sql"
"github.com/facebookincubator/ent/dialect/sql/sqlgraph"
"github.com/facebookincubator/ent/entc/integration/migrate"
"github.com/facebookincubator/ent/entc/integration/migrate/migratetest"
"github.com/facebookincubator/ent/entc/integration/migrate/testhelper"
"github.com/facebookincubator/ent/schema/field"
"github.com/facebookincubator/ent/schema/index"
"github.com/facebookincubator/ent/schema/mixin"
"github.com/facebookincubator/ent/schema/privacy"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
field.Int("age"),
}
}
// Mixin of the User.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
mixin.Time{},
}
}
// Index of the User.
func (User) Indexes() []ent.Index {
return []ent.Index{
// unique index.
index.Fields("name").Unique(),
// index for multiple fields.
index.Fields("name", "age"),
}
}
// Policy of the User.
func (User) Policy() ent.Policy {
return privacy.Policy{
Query: privacy.QueryPolicy{
Rules: privacy.AllowReadRule(),
},
Mutation: privacy.MutationPolicy{
Rules: privacy.AllowWriteRule(),
},
}
}
// CreateUserRequest holds the parameters for creating a new user.
type CreateUserRequest struct {
Name string `json:"name"`
Age int `json:"age"`
}
// UpdateUserRequest holds the parameters for updating an existing user.
type UpdateUserRequest struct {
Name string `json:"name"`
Age int `json:"age"`
}
// GetUserResponse holds the response for getting a single user.
type GetUserResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
// CreateUser creates a new user.
func CreateUser(c *gin.Context) {
var req CreateUserRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, err := client.User.
Create().
SetName(req.Name).
SetAge(req.Age).
Save(context.Background())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"id": user.ID})
}
// UpdateUser updates an existing user.
func UpdateUser(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var req UpdateUserRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, err := client.User.
Update().
Where(user.ID(id)).
SetName(req.Name).
SetAge(req.Age).
Save(context.Background())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"id": user.ID})
}
// DeleteUser deletes an existing user.
func DeleteUser(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := client.User.
DeleteOneID(id).
Exec(context.Background()); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
// GetUser gets a single user by ID.
func GetUser(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
user, err := client.User.
Query().
Where(user.ID(id)).
Only(context.Background())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
resp := GetUserResponse{
ID: user.ID,
Name: user.Name,
Age: user.Age,
}
c.JSON(http.StatusOK, resp)
}
func main() {
// Create a new gin router.
r := gin.Default()
// Create a new ent client.
client, err := ent.NewClient(ent.Driver(sqlgraph.New(sql.OpenDB("sqlite3", ":memory:")))))
if err != nil {
panic(err)
}
defer client.Close()
// Run migrations.
if err := client.Schema.Create(context.Background(), migrate.WithGlobalUniqueID(true)); err != nil {
panic(err)
}
// Setup routes.
r.POST("/users", CreateUser)
r.PUT("/users/:id", UpdateUser)
r.DELETE("/users/:id", DeleteUser)
r.GET("/users/:id", GetUser)
// Start listening.
if err := r.Run(":8080"); err != nil {
panic(err)
}
}
```
以上代码使用了 gin 和 ent 框架,提供了四个接口分别用于创建、更新、删除和查询用户。您可以使用 POST 请求发送 JSON 格式的数据来创建新用户,使用 PUT 请求发送 JSON 格式的数据来更新现有用户,使用 DELETE 请求删除现有用户,使用 GET 请求查询现有用户。
阅读全文