Currently, Hertz supports Linux, macOS, and Windows systems.
After you have prepared the Golang environment, this chapter will help you to get familiar with Hertz in a very short time.
First, you need to install the commend tool hz which is used in this chapter
GOPATH
environment has been defined correctly (For example export GOPATH=~/go
)
and the $GOPATH/bin
has been added to PATH
environment (For example export PATH=$GOPATH/bin:$PATH
);
Attention, do not set GOPATH
to a directory that the current user does not have read/write access to.go install github.com/cloudwego/hertz/cmd/hz@latest
For more information on how to use hz, please refer to: hz
$GOPATH/src
, you will need to create an additional dictionary in $GOPATH/src
and retrieve your code from that dictionary. $ mkdir -p $(go env GOPATH)/src/github.com/cloudwego
$ cd $(go env GOPATH)/src/github.com/cloudwego
hz new
$ go mod tidy
If you are currently using a Windows system, you can write the following sample code.
main.go
filemain.go
filepackage main
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)
func main() {
h := server.Default()
h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"message": "pong"})
})
h.Spin()
}
go.mod
file $ go mod init hertz_demo
$ go mod tidy
After you have completed the previous steps, you are able to compile & launch the server
$ go build -o hertz_demo && ./hertz_demo
If the server is launched successfully, you will see following message
2022/05/17 21:47:09.626332 engine.go:567: [Debug] HERTZ: Method=GET absolutePath=/ping --> handlerName=main.main.func1 (num=2 handlers)
2022/05/17 21:47:09.629874 transport.go:84: [Info] HERTZ: HTTP server listening on address=[::]:8888
Then, we can test the interface
$ curl http://127.0.0.1:8888/ping
If nothing goes wrong, we can see the following output
$ {"message":"pong"}
You have now successfully launched Hertz Server successfully and completed an API call. More API examples can be found at API Examples.
As for the layout of the Project Dictionary, here is a sample project layout that you can refer to. You can also organise the layout according to your business scenario.
As for the project directory structure, you may check Project Layout for reference, it can be organized according to the actual situation of the business logic.
Please refer:hertz-examples