I am trying to perform CRUD operation to golang with Mysql but whenever I try to post data it says 201 but it is not store to mysql.
Here is my controller: data-controller.go
func (c *dataController) Insert(context *gin.Context) {
var dataCreateDTO dto.DataCreateDTO
errDTO := context.ShouldBind(&dataCreateDTO)
if errDTO != nil {
res := helper.BuildErrorResponse("Failed to process request", errDTO.Error(), helper.EmptyObj{})
context.JSON(http.StatusBadRequest, res)
} else {
result := c.dataService.Insert(dataCreateDTO)
response := helper.BuildResponse(true, "OK", result)
context.JSON(http.StatusCreated, response)
}
}
data-dto.go
//DataCreateDTO is is a model that client use when create a new task
type DataCreateDTO struct {
ID uint64 `gorm:"primary_key:auto_increment" json:"id"`
Title string `gorm:"type:varchar(255)" json:"title"`
CreatedAt time.Time
}
my entity file is data.go
//Data struct represents data table in database
type Data struct {
ID uint64 `gorm:"primary_key:auto_increment" json:"id"`
Title string `gorm:"type:varchar(255)" json:"title"`
CreatedAt time.Time
}
my repository data-repository.go
//DataRepository is a ....
type DataRepository interface {
InsertData(b entity.Data) entity.Data
UpdateData(b entity.Data) entity.Data
DeleteData(b entity.Data)
AllData() []entity.Data
FindDataByID(dataID uint64) entity.Data
}
type dataConnection struct {
connection *gorm.DB
}
//NewDataRepository creates an instance DataRepository
func NewDataRepository(dbConn *gorm.DB) DataRepository {
return &dataConnection{
connection: dbConn,
}
}
func (db *dataConnection) InsertData(b entity.Data) entity.Data {
db.connection.Save(&b)
return b
}
my service data-service.go
//DataService is a ....
type DataService interface {
Insert(b dto.DataCreateDTO) entity.Data
Update(b dto.DataUpdateDTO) entity.Data
Delete(b entity.Data)
All() []entity.Data
FindByID(dataID uint64) entity.Data
}
type dataService struct {
dataRepository repository.DataRepository
}
//NewDataService .....
func NewDataService(dataRepo repository.DataRepository) DataService {
return &dataService{
dataRepository: dataRepo,
}
}
func (service *dataService) Insert(b dto.DataCreateDTO) entity.Data {
data := entity.Data{}
err := smapping.FillStruct(&data, smapping.MapFields(&b))
if err != nil {
log.Fatalf("Failed map %v: ", err)
}
res := service.dataRepository.InsertData(data)
return res
}
Main file that is server.go
var (
db *gorm.DB = config.SetupDatabaseConnection()
dataRepository repository.DataRepository = repository.NewDataRepository(db)
dataService service.DataService = service.NewDataService(dataRepository)
dataController controller.DataController = controller.NewDataController(dataService)
)
func main() {
defer config.CloseDatabaseConnection(db)
r := gin.Default()
dataRoutes := r.Group("api/datas")
{
dataRoutes.GET("/", dataController.All)
dataRoutes.POST("/", dataController.Insert)
dataRoutes.GET("/:id", dataController.FindByID)
dataRoutes.PUT("/:id", dataController.Update)
dataRoutes.DELETE("/:id", dataController.Delete)
}
r.Run()
}
when I do go run server.go It doesnot show any error but every time I do POST request it says 201k but when I do GET request to get all data it shows null.
my config for database is config.go
func SetupDatabaseConnection() *gorm.DB {
errEnv := godotenv.Load()
if errEnv != nil {
panic("Failed to load env file")
}
dbUser := os.Getenv("DB_USER")
dbPass := os.Getenv("DB_PASS")
dbHost := os.Getenv("DB_HOST")
dbName := os.Getenv("DB_NAME")
dsn := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8&parseTime=True&loc=Local", dbUser, dbPass, dbHost, dbName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("Failed to create a connection to database")
}
db.AutoMigrate(&entity.Data{})
return db
}
//CloseDatabaseConnection method is closing a connection between your app and your db
func CloseDatabaseConnection(db *gorm.DB) {
dbSQL, err := db.DB()
if err != nil {
panic("Failed to close connection from database")
}
dbSQL.Close()
}
Can you i please help me where I went wrong ? Thank you!