DTO: note_dto.go
package dtoimport "king/model"type NoteAddDTO struct {ID uintTitle string `json:"title" form:"title" binding:"required" message:"标题不能为空"`Content string `json:"content" form:"content" binding:"required" message:"内容不能为空"`UserID uint `json:"userId" form:"userId" binding:"required" message:"用户ID不能为空"`
}func (m *NoteAddDTO)ConverToModel (iNote *model.Note) {iNote.Title = m.TitleiNote.Content = m.ContentiNote.UserID = m.UserID
}
Model:note.go
package modelimport "gorm.io/gorm"type Note struct {gorm.ModelTitle string `json:"title" gorm:"size:64;not null"`Content string `json:"content" gorm:"not null"`UserID uint `json:"user_id" gorm:"not null"`
}
Dao:note_dao.go
package daoimport ("king/model""king/service/dto"
)var noteDao *NoteDaotype NoteDao struct {BaseDao
}func NewNoteDao() *NoteDao {if noteDao == nil {noteDao = &NoteDao{NewBaseDao(),}}return noteDao
}func (m *NoteDao) AddNote(iNoteAddDTO *dto.NoteAddDTO) error{var iNote model.NoteiNoteAddDTO.ConverToModel(&iNote)err := m.Orm.Create(&iNote).Errorif err == nil {iNoteAddDTO.ID = iNote.ID}return err
}
Service:note_service.go
package serviceimport ("king/dao""king/service/dto"
)var noteService *NoteServicetype NoteService struct {BaseServiceDao *dao.NoteDao
}func NewNoteService() *NoteService{if noteService == nil {noteService = &NoteService{Dao: dao.NewNoteDao(),}}return noteService
}func (m *NoteService) AddNote(iNoteAddDTO *dto.NoteAddDTO) error{return m.Dao.AddNote(iNoteAddDTO)
}
API:note_api.go
package apiimport ("king/service""king/service/dto""net/http""github.com/gin-gonic/gin"
)const (ERR_CODE_ADD_NOTE = 10021
)type NoteApi struct {BaseApiService *service.NoteService
}func NewNoteApi() NoteApi{return NoteApi{BaseApi: NewBaseApi(),Service: service.NewNoteService(),}
}func (m NoteApi)AddNote(c *gin.Context) {var iNoteAddDTO dto.NoteAddDTOif err := m.BuildRequest(BuildRequestOption{Ctx: c, DTO: &iNoteAddDTO}).GetError(); err != nil {return }err := m.Service.AddNote(&iNoteAddDTO)if err != nil {m.ServerFail(ResponseJson{Code: ERR_CODE_ADD_NOTE,Status: http.StatusBadRequest,Msg: "新增文章失败",})return}m.OK(ResponseJson{Code: SUCCESS,Msg: "新增文章成功",Data: iNoteAddDTO,})
}
Router:note.go
package routerimport ("king/api""github.com/gin-gonic/gin"
)func InitNoteRoutes() {RegistRoute(func(rgPublic *gin.RouterGroup, rgAuth *gin.RouterGroup) {noteApi := api.NewNoteApi()rgAuthNote := rgAuth.Group("note"){rgAuthNote.POST("", noteApi.AddNote)}})
}
Routers:router.go
func initBasePlatformRoutes() {InitNoteRoutes()
}
db:AutoMigrate
db.AutoMigrate(&model.Note{})
效果