Files
go-admin/common/actions/create.go
T
zhangwenjian ea2d807071 fix🐛: give queries the request's context, not the pooled gin.Context
WithContextDb and the five CRUD actions passed the *gin.Context itself
to GORM as the query's context. database/sql watches the context of a
query that returns rows inside a transaction from a goroutine of its
own, which can still read it after the handler returns - and gin hands
that Context to the next request as soon as the handler returns. GORM
wraps every write in a transaction, and an INSERT on SQLite or
PostgreSQL returns the new key as a row, so any write raced with the
next request's reset. The race detector reports it on the second of
two sequential requests.

They now pass c.Request.Context(), which belongs to one request only
and is cancelled when its client goes away.
2026-09-27 20:45:45 +08:00

50 lines
1.2 KiB
Go

package actions
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/v2/jwtauth/user"
"github.com/go-admin-team/go-admin-core/v2/response"
"github.com/go-admin-team/go-admin-core/v2/sdk/api"
"github.com/go-admin-team/go-admin-core/v2/sdk/pkg"
"go-admin/common/dto"
"go-admin/common/models"
)
// CreateAction 通用新增动作
func CreateAction(control dto.Control) gin.HandlerFunc {
return func(c *gin.Context) {
log := api.GetRequestLogger(c)
db, err := pkg.GetOrm(c)
if err != nil {
log.Error(err)
return
}
//新增操作
req := control.Generate()
err = req.Bind(c)
if err != nil {
response.Error(c, http.StatusUnprocessableEntity, err, err.Error())
return
}
var object models.ActiveRecord
object, err = req.GenerateM()
if err != nil {
response.Error(c, 500, err, "模型生成失败")
return
}
object.SetCreateBy(user.GetUserId(c))
err = db.WithContext(c.Request.Context()).Create(object).Error
if err != nil {
log.Errorf("Create error: %s", err)
response.Error(c, 500, err, "创建失败")
return
}
response.OK(c, object.GetId(), "创建成功")
c.Next()
}
}