使用過grpc的同學都知道,寫proto文件比較繁瑣,尤其是寫message,對應很多字段,爲此寫了一個簡單的從mysql直接讀取表結構,生成proto文件的工具。
工具的使用很簡單,需要簡單的配置,即可運行生成proto文件。
項目地址:https://github.com/guyan0319/...
使用說明:
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)
}