Go-Swagger: User Registration with MySql & Go
Go has really gained a lot of momentum in the market. Combining Go with swagger using go-swagger, makes it a very powerful yet simple web framework to work with.
If you are new to go-swagger then I’ll strongly recommend to read my introductory article. In the intro, I have explained the steps to install go-swagger
on your local machine. Later you can refer the implementation part in another article of mine. If you have this knowledge, then you can skip and go ahead in this article.
Prerequisite:
- Install MySql into your machine and create a schema named
ecommerce
. Have username and password asroot
(you can change it as well, but make sure you make necessary change inclient_builder.go
as shown below ) - Run below
SQL
query inecommerce
schema to create TABLE:
CREATE TABLE `ecommerce`.`customer`
(
`customerId` INT NOT NULL AUTO_INCREMENT,
`firstName` VARCHAR(45) NOT NULL,
`lastName` VARCHAR(45) NULL,
`phoneNo` INT NULL,
`password` VARCHAR(10) NULL,
`email` VARCHAR(60) NOT NULL,
PRIMARY KEY (`email`),
UNIQUE INDEX `phoneNo_UNIQUE` (`phoneNo` ASC) VISIBLE,
UNIQUE INDEX `id_UNIQUE` (`customerId` ASC) VISIBLE
);
Step 1: Create swagger file
To start with the development of this new endpoint, you need to recognize the model of request & response
and define them inswagger.yaml
file as below :
/register
endpoint which is of typePOST
.- Created
request
payload model namedRegisterUser
which containesemail
,fname
,lname
,password
&phoneNo
. - Created
response
payload model namedSuccessResponse
.
You can copy-paste & use online swagger editor to visualize this swagger file
Step 2: Generate boilerplate code using swagger file
Once we have the swagger.yaml
file ready, we can use below command to generate the swagger generated code:
swagger generate server -f swagger.yaml --default-scheme http --exclude-main
For better visualization, you can refer to the final code which I have created using these steps, in my GitHub e-commerce server code . In the GitHub code, I have kept the
swagger.yaml
under/api
folder. You need to go into/api
folder and runswagger generate
command as mentioned above.
Step 3: Install MySql package and shareable DB connection
- Install Mysql go package using
go get -u github.com/go-sql-driver/mysql
- Create a
client_builder.go
underclients
folder & importmysql
connection driver and to use it across all endpoints.
- Navigate to
api/restapi/configure_e_food.go
and go tofunc configureAPI()
to create a connection client object as below:
func configureAPI(api *operations.EFoodAPI) http.Handler {
clientBuilder := clients.NewClientBuilder()
dbClient := clientBuilder.BuildSqlClient() // dbClient can be injected to APIs
// .... remaining code here
}
Step 4: Create DAO struct to manage Customer details
- Create
./pkg/dao/customer.go
file with a function to insert new user details - Since we want to save password in Database without exposing to other users as well as system admins, we’ll be encrypting it using
bcrypt
package. To installbcrypt
, we can run below command:
go get -u golang.org/x/crypto/bcrypt
- Below is the final code which uses
bcrypt
to encrypt the user password.
Note : The *models.RegisterUser type in the args has been created by swagger.yaml when we ran swagger generator command.
Step 5: Attach DAO function with Endpoint
Now, that we have all the code in place, we can simply wireup the RegisterNewUser
function with /register
endpoint. To do that:
- Create
./handlers/post_register_user.go
file and write code as below. The final code with Dependency Injected can be found here.
Are you wondering what just happened in this code ? Check out this article of mine to understand the project structuring.
- Go to
configure_e_food.go
file and writeapi.UserRegisterHandler
:
Step 6: Make HTTP call to get response
Run the code using :
go run cmd\e-food-server\main.go — scheme http — port=8080
Go to postman and try hitting POST endpoint http://127.0.0.1:8080/v1/register
And that’s it !
In my next tutorial (coming soon …) , I’ll show you how to login using JWT for the registered user
To explore authentication of the registered user, you can read below article
If you liked what you read, please 👏 👏 clap 👏 👏 few times to encourage me 🐼 for writing such articles. Cheers !!