Introduction
In the previous post, we gave a brief introduction to the high-performance Go HTTP framework Hertz and completed a simple demo using Hertz to get you started.
In this post, you’ll learn more about using the Hertz framework with an official demo.
And we’ll highlight the following features:
-
Use
thrift
IDL to defineHTTP
interface -
Use
hz
to generate code -
Use
Hertz
binding and validate -
Use
GORM
andMySQL
Installation
Run the following command to get the official demo:
Project Structure
This is the basic architecture for the project. It’s pretty clean and simple, and hz
generated a lot of scaffolding code for us as well.
Define IDL
hz
is a tool provided by the Hertz framework for generating code. Currently, hz can generate scaffolding for Hertz projects based on thrift and protobuf IDL.
The definition of an excellent IDL file plays an important role in developing with Hertz. We will use the thrift IDL for this project as an example.
We can use api annotations to let hz
help us with parameter binding and validation, route registration code generation, etc.
hz
will generate the go tag based on the following api annotations so that Hertz can retrieve these values using reflection and parse them.
Field Annotation
The go-tagexpr open source library is used for parameter binding and validation of the Field annotation, as shown in the following example for CreateUserRequest
:
The form
annotation allows hz
to automatically bind the parameters in the form of an HTTP request body for us, saving us the trouble of manually binding them using methods such as PostForm
.
The vd
annotation allows for parameter validation. For example, CreateUserRequest
uses the vd
annotation to ensure that the gender
field is only 1 or 2.
You may refer to here for more information about parameter validation syntax.
Method Annotation
The Method annotation can be used to generate route registration code.
Consider the following UserService:
We defined POST methods and routes using post
annotations, and hz
will generate handler methods for each route as well as route grouping, middleware embedding scaffolding, etc. As shown in biz/router/user_gorm/api.go
and biz/handler/user_gorm/user_service.go
.
And we can also define the business error code in the idl file:
hz
will generate constants and related methods for us based on these.
Generate Code with hz
After we finish writing IDL, we can generate the scaffolding code for us by using hz
.
Execute the following command to generate code:
Execute the following command to update the code if you edit the IDL after the first generated:
Of course, the project has already generated the code for you, so you don’t need to execute it. When you actually use Hertz for web development yourself, I’m sure you’ll find it a very efficient and fun tool.
Use Middleware
In this project, we configured the root route group to use the gzip middleware for all routes to improve performance.
Just add one line of code to the generated scaffolding code, very easy. You can also refer to the hertz-contrib/gzip for more custom configuration.
Manipulating database with GORM
Configure GORM
To use GORM
with a database, you first need to connect to the database using a driver and configure GORM
, as shown in biz/dal/mysql/init.go
.
Here we connect with MySQL database by means of DSN and maintain a global database operation object DB
.
In terms of GORM configuration, since this project does not involve the operation of multiple tables at the same time, we can configure SkipDefaultTransaction
to true
to skip the default transaction, and enable caching through PrepareStmt
to improve efficiency.
We also use the default logger so that we can clearly see the SQL
generated for us by GORM.
Manipulating MySQL
GORM
concatenates SQL
statements to perform CRUD, so the code is very concise and easy to read, where all the database operations are in biz/dal/mysql/user.go
.
We also declare a model corresponding to the database table, the gorm.Model
contains some common fields, which GORM
can automatically fill in for us, and support operations such as soft deletion.
Handle HTTP Request
In this section, we’ll explore the handler (biz/handler/user_gorm/user_service.go
), which is the main business logic code.
CreateUser & DeleteUser & UpdateUser
CreateUser
Since we are using api annotations in the thift IDL, BindAndValidate
will do the parameter binding and validation for us . Very conveniently, all valid parameters will be injected into CreateUserRequest
.
If there is an error, we can use the JSON
method to return the data in JSON format . Whether it is CreateUserResponse
or the business code, we can directly use the code generated by hz
.
After that, we can insert a new user into MySQL by calling the CreateUser
in the dal
layer, passing in the encapsulated arguments.
If there is an error, we return JSON with the error code and information, just like we did in the beginning. Otherwise, the correct service code is returned to represent the successful creation of the user.
DeleteUser
The logic for DeleteUser
and CreateUser
is almost identical: Bind and validate the arguments, use mysql.DeleteUser
to delete the user, and return if there is an error, otherwise, return success.
UpdateUser
UpdateUser
is much the same, with the notable model transformation from an object that receives HTTP request parameters to a data access object that corresponds to a database table.
QueryUser
What’s worth noting in QueryUser
is that we’re doing paging and a transformation from model.User
to user_gorm.User
, which is the reverse of the operation we just mentioned in UpdateUser.
With a simple paging formula startIndex = (currentPage - 1) * pageSize
, we’re paging the data as we’re querying it.
And this time we’ve wrapped our transformation model in biz/pack/user.go
.
The rest of the business logic is the same as before, and we’re done with all the handler functions.
Run Demo
- Run mysql docker
- Generate MySQL table
Connect MySQL and execute user.sql
- Run demo
Summary
That’s it for this post. Hopefully it will give you a quick overview of how to develop with Hertz
and GORM
. Both of them are well documented . Feel free to check out the official documentation for more information.