delete.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package actions
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "device-manage/common/dto"
  6. "device-manage/common/log"
  7. "device-manage/common/models"
  8. "device-manage/tools"
  9. "device-manage/tools/app"
  10. )
  11. // DeleteAction 通用删除动作
  12. func DeleteAction(control dto.Control) gin.HandlerFunc {
  13. return func(c *gin.Context) {
  14. db, err := tools.GetOrm(c)
  15. if err != nil {
  16. log.Error(err)
  17. return
  18. }
  19. msgID := tools.GenerateMsgIDFromContext(c)
  20. //删除操作
  21. req := control.Generate()
  22. err = req.Bind(c)
  23. if err != nil {
  24. log.Errorf("MsgID[%s] Bind error: %s", msgID, err)
  25. app.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
  26. return
  27. }
  28. var object models.ActiveRecord
  29. object, err = req.GenerateM()
  30. if err != nil {
  31. app.Error(c, http.StatusInternalServerError, err, "模型生成失败")
  32. return
  33. }
  34. object.SetUpdateBy(tools.GetUserIdUint(c))
  35. //数据权限检查
  36. p := GetPermissionFromContext(c)
  37. db = db.WithContext(c).Scopes(
  38. Permission(object.TableName(), p),
  39. ).Where(req.GetId()).Delete(object)
  40. if db.Error != nil {
  41. log.Errorf("MsgID[%s] Delete error: %s", msgID, err)
  42. app.Error(c, http.StatusInternalServerError, err, "删除失败")
  43. return
  44. }
  45. if db.RowsAffected == 0 {
  46. app.Error(c, http.StatusForbidden, nil, "无权删除该数据")
  47. return
  48. }
  49. app.OK(c, object.GetId(), "删除成功")
  50. c.Next()
  51. }
  52. }