apicontroller.tpl 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package v1
  2. import (
  3. "github.com/runningwater/gohub/app/models/{{PackageName}}"
  4. "github.com/runningwater/gohub/app/policies"
  5. "github.com/runningwater/gohub/app/requests"
  6. "github.com/runningwater/gohub/pkg/response"
  7. "github.com/gin-gonic/gin"
  8. )
  9. type {{StructNamePlural}}Controller struct {
  10. BaseApiController
  11. }
  12. func (ctrl *{{StructNamePlural}}Controller) Index(c *gin.Context) {
  13. {{VariableNamePlural}} := {{PackageName}}.All()
  14. response.Data(c, {{VariableNamePlural}})
  15. }
  16. func (ctrl *{{StructNamePlural}}Controller) Show(c *gin.Context) {
  17. {{VariableName}}Model := {{PackageName}}.Get(c.Param("id"))
  18. if {{VariableName}}Model.ID == 0 {
  19. response.Abort404(c)
  20. return
  21. }
  22. response.Data(c, {{VariableName}}Model)
  23. }
  24. func (ctrl *{{StructNamePlural}}Controller) Store(c *gin.Context) {
  25. request := requests.{{StructName}}Request{}
  26. if ok := requests.Validate(c, &request, requests.{{StructName}}Save); !ok {
  27. return
  28. }
  29. {{VariableName}}Model := {{PackageName}}.{{StructName}}{
  30. FieldName: request.FieldName,
  31. }
  32. {{VariableName}}Model.Create()
  33. if {{VariableName}}Model.ID > 0 {
  34. response.Created(c, {{VariableName}}Model)
  35. } else {
  36. response.Abort500(c, "创建失败,请稍后尝试~")
  37. }
  38. }
  39. func (ctrl *{{StructNamePlural}}Controller) Update(c *gin.Context) {
  40. {{VariableName}}Model := {{PackageName}}.Get(c.Param("id"))
  41. if {{VariableName}}Model.ID == 0 {
  42. response.Abort404(c)
  43. return
  44. }
  45. if ok := policies.CanModify{{StructName}}(c, {{VariableName}}Model); !ok {
  46. response.Abort403(c)
  47. return
  48. }
  49. request := requests.{{StructName}}Request{}
  50. bindOk, errs := requests.Validate(c, &request, requests.{{StructName}}Save)
  51. if !bindOk {
  52. return
  53. }
  54. if len(errs) > 0 {
  55. response.ValidationError(c, errs)
  56. return
  57. }
  58. {{VariableName}}Model.FieldName = request.FieldName
  59. rowsAffected := {{VariableName}}Model.Save()
  60. if rowsAffected > 0 {
  61. response.Data(c, {{VariableName}}Model)
  62. } else {
  63. response.Abort500(c, "更新失败,请稍后尝试~")
  64. }
  65. }
  66. func (ctrl *{{StructNamePlural}}Controller) Delete(c *gin.Context) {
  67. {{VariableName}}Model := {{PackageName}}.Get(c.Param("id"))
  68. if {{VariableName}}Model.ID == 0 {
  69. response.Abort404(c)
  70. return
  71. }
  72. if ok := policies.CanModify{{StructName}}(c, {{VariableName}}Model); !ok {
  73. response.Abort403(c)
  74. return
  75. }
  76. rowsAffected := {{VariableName}}Model.Delete()
  77. if rowsAffected > 0 {
  78. response.Success(c)
  79. return
  80. }
  81. response.Abort500(c, "删除失败,请稍后尝试~")
  82. }