吾八哥博客

您现在的位置是:首页 > 码农手记 > Golang > 正文

Golang

基于gin框架实现的脚手架工具ginhelper用法介绍

吾八哥2022-05-22Golang31836

ginhelper是用于gin框架快速开发的辅助工具,支持monorepo方式,使用方法如下:

安装ginhelper

go install github.com/5bug/ginhelper@latest

等待安装完成后,查看使用帮助提示:

➜  ~ ginhelper -h
Usage:
  ginhelper [command]

Available Commands:
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command
  new         create an app template
  update      update app api and service

Flags:
  -h, --help      help for ginhelper
  -v, --version   version for ginhelper

Use "ginhelper [command] --help" for more information about a command.

快速开发

初始化工程

➜  ~/codes mkdir test
➜  ~/codes cd test
➜  ~/codes/test ginhelper new
? What is project name ? github.com/5bug/test
? What is app name ? demo1

创建好的工程目录为:

➜  ~/codes/test tree .
.
├── cmd
│   └── demo1
│       └── main.go
├── go.mod
├── internal
│   └── demo1
│       ├── api
│       │   ├── api.go
│       │   ├── handlers.go
│       │   └── router.go
│       ├── conf
│       │   └── conf.go
│       └── service
│           ├── api.go
│           └── service.go
└── pkg
    ├── conf
    │   └── conf.go
    ├── rest
    │   ├── jwt.go
    │   ├── page.go
    │   ├── rest.go
    │   └── server.go
    └── storage
        └── storage.go

11 directories, 14 files

定义api文件

这里api定义使用纯go代码实现,通过注解来定义路由、请求方法、是否需要认证,具体注解说明如下:

  • @Router: 路由定义 /xxx [请求方法(get post put delete head)]

  • @Auth: 是否需要认证 true/false

api定义文件纯Go语法,使用成本低!例如在internal/demo1/api/目录下定义api文件user.go,内容如下:

package api

// UserRequest user request
// @Router /user [get]
// @Auth false
type UserRequest struct {
	ID int `json:"id" binding:"required"`
}

// UserReply user reply
type UserReply struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Sex   int    `json:"sex"`
	Email string `json:"email"`
}

自动生成代码

根据上面定义的api文件自动生成代码,上面的api定义在demo1的app里面,所以更新方法为:

ginhelper update -a demo1

这个时候api定义里的/user相关的路由请求代码自动生成好了,只需要在internal/demo1/service/user.go里实现自己的业务逻辑即可

编译运行

go mod tidy
...
go run cmd/demo1/main.go

开源地址

这里仅仅实现了基于gin框架的自动生成繁琐代码的方法,对于简单的服务来说能一定程度上提效,但对于成熟的脚手架工具来说远远还不够,代码开源地址为:

https://github.com/5bug/ginhelper