Connect to the MySQL Database

Learn how to connect the REST API application to the MySQL database.

Introduction

The storage used so far is not persistent, and the authentication feature has not been available. Let’s replace it with persistent storage using the MySQL database and add the authentication feature using the JSON Web Tokens (JWT) mechanism.

Before implementing those features, some additional libraries are added:

Before implementing those features, some additional libraries are added:

  • GORM: For object-relational mapping mechanism to the relational database.
  • GoDotEnv: For reading .env files.
  • JWT: For authentication mechanism.
  • Bcrypt: For password encryption.

We need to install these additional libraries with the following commands when running it independently. However, it has already been set up for you on the Educative platform.

We install the GORM library and its driver to perform query operations with the relational database.

go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

We then install the GoDotEnv library to read the configuration from the .env file.

go get github.com/joho/godotenv

We also install the JWT library to authenticate with JSON Web Token (JWT).

go get -u github.com/gofiber/jwt/v3
go get -u github.com/golang-jwt/jwt/v4

Finally, we install bcrypt to generate a password with encryption.

go get -u golang.org/x/crypto/bcrypt

Create a connection to the database

Note: The .env file is required if a local machine is used. However, it has already been set up for you on the Educative platform.

Before creating a connection to the database, we create a file called .env to store the database credentials. This file is also used to store the credentials for authentication with JWT. Inside the .env file, some fields are added for the database and JWT credentials. Make sure the credentials are matched with the MySQL database.

DB_HOST=localhost
DB_PORT=3306
DB_USER=root
DB_PASSWORD=
DB_NAME=inventory
JWT_SECRET_KEY=mysecretkey
JWT_SECRET_KEY_EXPIRE_MINUTES_COUNT=15

A directory called utils is created. In this directory, some helpers are created. The first helper is for reading database credentials or configurations from the .env file. Inside the utils directory, a new file called utils.go is created.

Get hands-on with 1400+ tech skills courses.