En este tutorial vamos a aprender a crear una API REST CRUD usando Go con GORM que es una ORM y la base de datos MySQL. Crearemos una API REST que desarrolle las peticiones CRUD (Create, Read, Update, Delete) usando el Framework Backend de Goland llamado Gin.
1- Init go
Ejecutar comando para instalar el framework gin, GORM, driver mysql. Recuerde que debe crear una carpeta llamado go\src\github.com\artyom-developer\nombre-proyecto dentro de Go que esta ubicado en la raiz principal del usuario por ejemplo lenovo-pc/go
mkdir go-backed & cd go-backend
go mod init tutofox.com/go-backend
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
2 – Test server
Crear archivo un archivo main.go en go\src\github.com\artyom-developer\go-backend\main.go
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "Hello world from server Go.", }) }) r.Run() }
Ejecutar servidor
go run main.go
3 – Database
Crear archivo un archivo y configurar la conexion de base de datos en go\src\github.com\artyom-developer\go-backend\configs/databse.go
package configs import ( "log" "gorm.io/driver/mysql" "gorm.io/gorm" ) var DB *gorm.DB func ConnectToDB() { var err error dsn := "root:password1234@tcp(127.0.0.1:3306)/databasename?charset=utf8mb4&parseTime=True&loc=Local" DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { log.Fatal("Failed to connect DB") } }
4 – Model
Crear un archivo modelo llamado PersonModel.go en go\src\github.com\artyom-developer\go-backend\models\PersonModel.go
package models import ( "time" "gorm.io/gorm" ) type Person struct { gorm.Model ID uint Name string Address string Phone uint CreatedAt time.Time UpdatedAt time.Time } func (Person) TableName() string { return "persons" }
5 – Migrate
Crear un archivo para ejecutar la migraciòn
go\src\github.com\artyom-developer\go-backend\migrate\migrate.go
package main import ( "tutofox.com/m/configs" "tutofox.com/m/models" ) func init() { configs.ConnectToDB() } func main() { configs.DB.AutoMigrate(&models.Person{}) }
go run migrate/migrate.go
6 – Controllers
Crear un archivo controllador
go\src\github.com\artyom-developer\go-backend\controllers\PersonController.go
package controllers import ( "github.com/gin-gonic/gin" "tutofox.com/m/configs" "tutofox.com/m/models" ) type PersonRequestBody struct { Name string `json:"name"` Address string `json:"address"` Phone uint `json:"phone"` } func PersonCreate(c *gin.Context) { body := PersonRequestBody{} c.BindJSON(&body) person := &models.Person{Name: body.Name, Address: body.Address, Phone: body.Phone} result := configs.DB.Create(&person) if result.Error != nil { c.JSON(500, gin.H{"Error": "Failed to insert"}) return } c.JSON(200, &person) } func PersonGet(c *gin.Context) { var persons []models.Person configs.DB.Find(&persons) c.JSON(200, &persons) return } func PersonGetById(c *gin.Context) { id := c.Param("id") var person models.Person configs.DB.First(&person, id) c.JSON(200, &person) return } func PersonUpdate(c *gin.Context) { id := c.Param("id") var person models.Person configs.DB.First(&person, id) body := PersonRequestBody{} c.BindJSON(&body) data := &models.Person{Name: body.Name, Address: body.Address, Phone: body.Phone} result := configs.DB.Model(&person).Updates(data) if result.Error != nil { c.JSON(500, gin.H{"Error": true, "message": "Failed to update"}) return } c.JSON(200, &person) } func PersonDelete(c *gin.Context) { id := c.Param("id") var person models.Person configs.DB.Delete(&person, id) c.JSON(200, gin.H{"deleted": true}) return }
7 – Routes
Crear un archivo routes
go\src\github.com\artyom-developer\go-backend\routes\PersonRoutes.go
package routes import ( "github.com/gin-gonic/gin" "tutofox.com/m/controllers" ) func PersonRouter(router *gin.Engine) { routes := router.Group("api/v1/persons") routes.POST("", controllers.PersonCreate) routes.GET("", controllers.PersonGet) routes.GET("/:id", controllers.PersonGetById) routes.PUT("/:id", controllers.PersonUpdate) routes.DELETE("/:id", controllers.PersonDelete) }
8 – Main server
go\src\github.com\artyom-developer\go-backend\main.go
package main import ( "net/http" "github.com/gin-gonic/gin" "tutofox.com/m/configs" "tutofox.com/m/routes" ) func init() { configs.ConnectToDB() } func main() { r := gin.Default() routes.PersonRouter(r) r.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "Hello world from server Go.", }) }) r.Run() }
go run main.go