Hertz 学习笔记(32)

201 阅读1分钟

还差一点学完 hz 相关的例子,再坚持一下。

使用 hz 自定义模版生成服务端代码的示例

这个项目要用到 makefile,有点不太明白。。。然后这个文件里面写的还是 bash 里能运行的命令:

init_api:
	hz new --mod=github.com/hertz/hello --idl=idl/hello.thrift --customize_package=template/package.yaml: --customize_layout=template/layout.yaml:

update_api:
	hz update --mod=github.com/hertz/hello --idl=idl/hello.thrift --customize_package=template/package.yaml: --customize_layout=template/layout.yaml:

项目目录结构如下:

.
├── biz
├── build.sh
├── conf
├── docker-compose.yaml
├── go.mod
├── idl
├── main.go
├── makefile
├── readme.md
├── script
└── template

biz 是生成的代码所在的文件夹,一点一点来看。

./biz
├── dal
│   ├── init.go
│   ├── mysql
│   │   └── init.go
│   └── redis
│       └── init.go
├── handler
│   └── hello
│       └── example
│           ├── hello_service.go
│           └── hello_service_test.go
├── model
│   └── hello
│       └── example
│           └── hello.go
├── router
│   ├── hello
│   │   └── example
│   │       ├── hello.go
│   │       └── middleware.go
│   └── register.go
├── service
│   ├── hello_method.go
│   └── hello_method_test.go
└── utils
    └── resp.go

dal 是存储层相关的代码。handler 里面的代码处理请求,验证后返回响应。route 是路由和中间件相关的代码。service 里面的代码是实际的业务逻辑。最后的 utils 里面封装了一些公共的方法。

这个项目要运行靠的是 build.sh,先来看这个文件:

#!/bin/bash
RUN_NAME=
mkdir -p output/bin output/conf
cp script/bootstrap.sh output 2>/dev/null
chmod +x output/bootstrap.sh
cp -r conf/* output/conf
go build -o output/bin/${RUN_NAME}

现在关键应该是这个 bootstrap.sh,这个文件在 script 文件夹里:

#!/bin/bash
CURDIR=$(cd $(dirname $0); pwd)
BinaryName=
echo "$CURDIR/bin/${BinaryName}"
exec $CURDIR/bin/${BinaryName}

这里直接是执行代码的编译结果