If you got to this point you have the main structure in place. What we are going to do next is to integrate MySQL into our API.
For that, we will be using GORM, which is an ORM (Object Relational Mapping) for Go.
Check if you have MySQL up and running on your machine. I have it running on port 3306 (default). Then create a database for our API, I will create as “figo”.
Let’s install GORM. Run the following command on your terminal to install our dependencies.
go get -u gorm.io/gorm go get -u gorm.io/driver/mysql
Go to your project and create the connector directory, with the mysql.go file. It will be pkg/connector/mysql.go.
package connector
import (
"fmt"
"os"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// Connect to the database
func Connect() *gorm.DB {
dbName := os.Getenv("DB_NAME")
dbUser := os.Getenv("DB_USER")
dbPass := os.Getenv("DB_PASS")
dbHost := os.Getenv("DB_HOST")
conn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", dbUser, dbPass, dbHost, "3306", dbName)
db, err := gorm.Open(mysql.Open(conn), &gorm.Config{})
if err != nil {
panic(err)
}
return db
}
We have three environment variables and then our connection string. We are passing our database user, password, host, port, and database name.
gorm.Open will get us the MySQL’s connection and with it, we can start to interact with MySQL.
We will need to change our main, route, handler, and entity files to include our new implementation.
Quick note, I will be omitting the imports, however, you can find the full code on the Bootmind’s Github repository https://github.com/bootmind/figo-api.
Go to our expense handler and update it to the ExpenseHandler (pkg/handler/ExpenseHandler) struct.
// ExpenseHandler type
type ExpenseHandler struct {
DB *gorm.DB
}
Now we will hold a pointer to our GORM instance, allowing us to list our expenses, for example.
Update the expense route Expenses (pkg/route/Expenses).
// Expenses route
func Expenses(app *fiber.App, db *gorm.DB) {
h := &handler.ExpenseHandler{
DB: db,
}
r := app.Group("/expenses")
r.Get("/", h.Index)
}
With the new parameter to receive our database connection and then passing it to our handler.
On our main.go
func main() {
app := fiber.New()
db := connector.Connect()
app.Get("/", func(c *fiber.Ctx) error {
return c.JSON(map[string]string{
"message": "Figo API",
})
})
route.Expenses(app, db)
app.Listen(":3000")
}
Creating the connection and passing it as an argument for our expenses’ route.
Go ahead and run to see if you get any errors. I will be passing the environment variables to our connection work properly, however for this step you need to use your configuration settings.
DB_NAME=figo DB_USER=root DB_PASS=4321 DB_HOST=172.17.0.2 go run .
Next let’s update our ExpenseEntity (pkg/entity/expense.go)
package entity
import (
"gorm.io/gorm"
)
// Expense type
type Expense struct {
gorm.Model
Title string `json:"title"`
Total float64 `json:"total"`
Attachment string `json:"attachment"`
}
The gorm.Model is an embed struct that will include extra fields to our struct and they are ID, CreatedAt, UpdatedAt, and DeletedAt.
Go to back to our pkg/connector/mysql.go and update it.
// Connect to the database
func Connect() *gorm.DB {
dbName := os.Getenv("DB_NAME")
dbUser := os.Getenv("DB_USER")
dbPass := os.Getenv("DB_PASS")
dbHost := os.Getenv("DB_HOST")
conn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", dbUser, dbPass, dbHost, "3306", dbName)
db, err := gorm.Open(mysql.Open(conn), &gorm.Config{})
if err != nil {
panic(err)
}
if os.Getenv("DB_MIGRATE") == "true" {
Migrate(db)
}
return db
}
// Migrate tables
func Migrate(db *gorm.DB) {
db.Migrator().CreateTable(&entity.Expense{})
}
We added the migrate function to create our table. Run again, but now we will add the DB_MIGRATE=true.
DB_NAME=figo DB_USER=root DB_PASS=4321 DB_HOST=172.17.0.2 DB_MIGRATE=true go run .
Then check your MySQL database and should see the expenses table created along with its columns.
Github repository: https://github.com/bootmind/figo-api
Part 01 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-01/
Part 02 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-02/
Part 04 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-04/
Part 05 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-05/

Leave a Reply