前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >导出mysql表结构生成grpc需要的proto文件工具

导出mysql表结构生成grpc需要的proto文件工具

作者头像
孤烟
发布2020-09-27 11:07:20
2.8K0
发布2020-09-27 11:07:20
举报
文章被收录于专栏:golang开发笔记golang开发笔记

使用过grpc的同学都知道,写proto文件比较繁琐,尤其是写message,对应很多字段,为此写了一个简单的从mysql直接读取表结构,生成proto文件的工具。

工具的使用很简单,需要简单的配置,即可运行生成proto文件。 项目地址:https://github.com/guyan0319/...

准备

使用前需先安装依赖包go-sql-driver/mysql

代码语言:javascript
复制
$ go get -u github.com/go-sql-driver/mysql

使用说明:

代码语言:javascript
复制
func main() {
    //模板文件存放路径
    tpl := "d:/gopath/src/mysql-to-proto/template/proto.go.tpl"
    //生成proto文件路径
    file := "d:/gopath/src/mysql-to-proto/sso.proto"
    //数据库名,这里填你自己的数据库名
    dbName := "user"
    //配置连接数据库信息
    db, err := Connect("mysql", "root:123456@tcp(127.0.0.1:3306)/"+dbName+"?charset=utf8mb4&parseTime=true")
    //Table names to be excluded
    //需要排除表,这里的表不会生成对应的proto文件
    exclude := map[string]int{"user_log": 1}
    if err != nil {
        fmt.Println(err)
    }
    if IsFile(file) {
        fmt.Fprintf(os.Stderr, "Fatal error: ", "proto file already exist")
        return
    }
    t := Table{}
    //配置message,Cat 
    t.Message = map[string]Detail{
        "Filter": {
            Name: "Filter",
            Cat:  "custom",
            Attr: []AttrDetail{{
                TypeName: "uint64", //类型
                AttrName: "id",//字段
            }},
        },
        "Request": {
            Name: "Request",
            Cat:  "all",
        },
        "Response": {
            Name: "Response",
            Cat:  "custom",
            Attr: []AttrDetail{
                {
                    TypeName: "uint64",
                    AttrName: "id",
                },
                {
                    TypeName: "bool",
                    AttrName: "success",
                },
            },
        },
    }
    //pachage名称
    t.PackageModels = "sso"
    //service名称
    t.ServiceName = "Sso"
    //配置services里面的rpc
    t.Method = map[string]MethodDetail{
        "Get":    {Request: t.Message["Filter"], Response: t.Message["Request"]},
        "Create": {Request: t.Message["Request"], Response: t.Message["Response"]},
        "Update": {Request: t.Message["Request"], Response: t.Message["Response"]},
    }
    //处理数据库表字段属性
    t.TableColumn(db, dbName, exclude)
    //生成proto
    t.Generate(file, tpl)
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 准备
  • 使用说明:
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档