What is Hertz
Hertz [həːts]
is a high-performance, high-usability, extensible HTTP framework for Go. It’s designed to simplify building microservices for developers.
Why Hertz
One of the highlights of Hertz is its extremely high performance. You can get an intuition for this by looking at the following statistics on echo requests.
- Horizontal Comparison
- Time Delay Comparison
You may refer to hertz-benchmark for more information.
Another point is its ease of use, which we’ll discuss next.
How to use Hertz
Here we’ll write a simple demo to help you get familiar with the basic features of the Hertz framework.
Installation
Before using Hertz, you need to set up your Golang development environment and make sure it’s >= v1.15.
Once we have our Golang environment ready, let’s create the project folder of our little demo which usually under $GOPATH/src
.
I highly recommend using the Hertz command-line tool hz
that comes with Hertz.
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’s IDL.
The code generated by hz
, part of it is generated by the underlying compiler (usually about the struct defined in IDL), and the other part is the user-defined routing, method and other information in IDL. The user can run the code directly.
In terms of execution flow, when hz
uses thrift IDL to generate code, hz calls thriftgo to generate the go struct code and executes itself as a plugin to thriftgo
(named thrift-gen-hertz) to generate the rest of the code. This is also true when used with the protobuf IDL.
You may refer to hz toolkit usage for more information.
Install hz with the following command:
If the hz
version information is displayed correctly as followed, then we have finished the installation and are ready with the base Hertz development environment.
Define IDL
In this section we will write the IDL file for our project userdemo
.
hz
can use thrift IDL or protobuf IDL to generate code and needs to install the appropriate compiler thriftgo or protoc. We will use thrift as an example.
Let’s create an idl folder and define user.thrift
.
As you can see, we have defined the HTTP request method and route in the form of api annotations. hz
will generate the route handler for us based on these annotations.
You may refer to Supported api annotations to get all the api annotations supported by hz
.
Generate Code
Execute the following command under the project directory. hz
will generate the scaffolding code for us.
If you modify user.thrift
that has generated code, you can also update the generated code by using the following command.
Here is the structure of the code generated by user.thrift
and what it means. A simple understanding of it will help you get started.
Use Middleware
Middleware can help with things like jwt authentication before or after the request has officially entered the handler function for processing.
Hertz supports a number of commonly used middleware. In this case, we’ll use Session middleware to help us count how many times a user has logged in.
As mentioned earlier, hz
helped us set up a lot of scaffolding codes. We only need to focus on the business code. To use Session middleware you just need to simply modify the _loginMw
method of middleware.go
as below.
Well, isn’t that easy?
Improve Handler
Next we’ll write the handler, specifically the user_service.go
file.
Hertz takes care of the simple validation of the data binding and some chores. All we need to do is handle the request.
Note: There are no database operations involved in this demo, all the data will be simply stored in a map structure with no persistent storage.
- Let’s look at the
Register
method first.
We can receive data from a Post request form via the PostForm
method. You can also use the String
or JSON
method to return string or JSON data to the client and specify the response status code.
- Next, let’s go though the
Login
method.
Most of these methods are similar to the Register
, except that we use Session middleware which is just set up to count how many times different users have logged in.
We can use the sessions.Default
method to retrieve the session object and use the Get
and Set
methods to edit the values stored in the session.
- Finally, let’s take a look at the
Info
method.
In this method, we’re using Hertz’s Parametric Route feature, which allows us to specify a route using a named parameter such as :name
, so that the parameter matches a path segment.
We set the :username
parameter route and use the Param
method to get the value in the request path.
For example, if your request path is /user/foobar
, then username will be foobar
.
Run userdemo
Execute the following commands under the project folder:
Hertz listens on local port 8888 by default. You can test this simply by running the following command:
If you receive the following response, congratulations on running this demo successfully!
Other Feature
If you look at the router/user/user.go
generated by hz
, you’ll see that Hertz automatically uses Route Group feature, which helps you sort and organize complex routes.
When we use server.Default
in main.go
, Hertz also registers the recover middleware for us by default, which handles panic gracefully.
Now that we’ve covered some of the main Hertz methods and how to use them, I hope this will help you get started with Hertz quickly.
Summary
This demo only covers a very small part of Hertz features. You can check out the cloudwego/hertz for more information. I’m sure the documentation has answers to all your questions.
The code of this demo is here. It’s just a simple example. There are many imperfections, but I would be happy if this could help you.