Go编译proto文件

1. 安装Go

1.1 下载Go

wget https://studygolang.com/dl/golang/go1.13.4.linux-amd64.tar.gz
# 解压
tar -zxvf go1.13.4.linux-amd64.tar.gz

1.2 配置go环境

编辑 /etc/profile 文件

vim ~/.bashrc

将下面内容加入到末尾(GOPAT是我Windows中的GOPATH)

export GOROOT=/usr/local/go
export GOPATH=/home/pibigstar/goWork
export PATH=$GOPATH/bin:$PATH
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

2. 工具安装

2.1 安装protoc

去这个网址下载:https://github.com/protocolbuffers/protobuf/releases,根据自己的系统,下载对应的文件
解压:

unzip protoc.zip 

将bin文件夹下的 protoc 复制到Linux 中的 /bin目录下

sudo cp protoc/bin/protoc /bin/protoc

执行 protoc -verson 如果输出版本信息则证明配置成功

2.2 安装protoc-gen-go

# 下载
git clone https://github.com/golang/protobuf.git
# 进入目录
cd protobuf/protoc-gen-go
# 编译
go install

2.3 安装protoc-gen-validate

这个是用来生成pb的校验规则文件,也就是*.pb.validate.go

go get -u github.com/envoyproxy/protoc-gen-validate

2.4 安装protoc-gen-grpc-gateway

这个是用来生成让grpc支持http调用的

git clone https://github.com/grpc-ecosystem/grpc-gateway.git
# 安装 protoc-gen-grpc-gateway
cd grpc-gateway/protoc-gen-grpc-gateway
go install .
# 安装protoc-gen-swagger
cd grpc-gateway/protoc-gen-swagger
go install .

2.5 安装protoc-gen-doc

这个是用来生成 proto 的文档文件,会生成一个 html 格式的文档, 下载地址:https://github.com/pseudomuto/protoc-gen-doc/releases

wget https://github.com/pseudomuto/protoc-gen-doc/releases/download/v1.3.0/protoc-gen-doc-1.3.0.windows-amd64.go1.11.2.tar.gz

# 解压
tar -zxvf protoc-gen-doc-1.3.0.windows-amd64.go1.11.2.tar.gz

2.6 安装proto-gen-java

可在这个地址下载 protoc-gen-java工具,https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/ ,记得把文件名改为protoc-gen-grpc-java.exe

3. 编译

3.1 hello.proto

hello.proto

syntax="proto3";

package main;

message Hello {
	string value = 1;
}

3.2 编译

3.2.1 编译为Go代码(protoc-gen-go)

protoc --go_out=plugins=grpc,paths=source_relative:. --validate_out="lang=go,paths=source_relative:." hello.proto

注意

  • paths参数
    使用 source_relative 则不会使用option go_package中指定的路径
    使用 import 则是使用option go_package 中指定的路径

3.2.2 编译为Java代码 (protoc-gen-java)

可在这个地址下载 protoc-gen-java工具,https://repo1.maven.org/maven2/io/grpc/protoc-gen-grpc-java/1.0.1/ ,记得把文件名改为protoc-gen-grpc-java.exe

protoc --java_out=. --grpc-java_out=. hello.proto

3.2.3 生成proto文档(proto-gen-doc)

protoc --doc_out=. --doc_opt=html,index.html:Ignore* hello.proto user.proto

3.3 复杂点的proto

syntax="proto3";

//生成的pb文件中package为admin
package admin;

//生成go文件的路径
option go_package          = "pb/admin";
//关闭Java多文件
option java_multiple_files = false;
//生成的Java文件的package路径
option java_package        = "pb.admin";

service UserService {
	rpc Login(LoginReq) returns (LoginResp);
}

message LoginReq {
	string username = 1;
	string password = 2;
}

message LoginResp {
	int32 code = 1;
    string msg = 2;
}

3.4 生成gw.pb文件

proto 导入 google/api/annotations.proto

syntax = "proto3";

package pb;
option go_package  = "pb/echo";

import "google/api/annotations.proto";

service Echo {
    rpc UnaryEcho (EchoRequest) returns (EchoResponse){
        option (google.api.http) = {
            post: "/v1/example/echo"
            body: "*"
        };
    }
}

// EchoRequest is the request for echo.
message EchoRequest {
    string message = 1;
}

// EchoResponse is the response for echo.
message EchoResponse {
    string message = 1;
}

下载地址: https://github.com/googleapis/googleapis/tree/master/google
在proto下面将 google的api 放进去
在这里插入图片描述
编译时用 -I 命令 引入 extra/src 下面的文件

protoc -I=extra/src:. \
--grpc-gateway_out=logtostderr=true:pb \
--go_out=plugins=grpc,paths=import:pb echo.proto

3.5 编译脚本

#!/usr/bin/env bash

TARGET="../"

if [ -n "$1" ]; then
    TARGET=$1
fi

# 排除掉 extra/src 目录
for file in `find . -path ./extra/src -prune -o -name '*.proto' -print`;
do
	echo $file
	protoc -I=extra/src:. --grpc-gateway_out=$TARGET\
	--go_out=plugins=grpc,paths=import:$TARGET \
	--validate_out="lang=go,paths=import:$TARGET" $file
done

3.6 代码注册

package main

import (
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"net/http"

	pb "data/proto/demo/echo"
)

func main() {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}
	err := pb.RegisterEchoHandlerFromEndpoint(ctx, mux, "127.0.0.1:6000", opts)
	if err != nil {
		return err
	}
	http.ListenAndServe(":8080", mux)
}
安装protobuf 1. 下载protobuf编译器:https://github.com/protocolbuffers/protobuf/releases 2. 安装protobuf编译器: ``` $ tar -xzvf protobuf-3.15.6.tar.gz $ cd protobuf-3.15.6/ $ ./configure $ make $ sudo make install $ sudo ldconfig ``` 3. 安装protobuf的Go语言支持: ``` $ go get github.com/golang/protobuf/protoc-gen-go ``` 该命令会从GitHub上下载并编译protoc-gen-go可执行文件,该文件是一个protobuf插件,用于将proto文件生成Go语言代码。 使用protobuf 1. 编写proto文件 ```protobuf syntax = "proto3"; package example; message Person { string name = 1; int32 age = 2; repeated string hobbies = 3; } ``` 2. 使用protoc命令生成Go语言代码 ``` $ protoc --go_out=. example.proto ``` 该命令会在当前目录下生成example.pb.go文件,其中包含了protobuf定义的Person类型的Go语言结构体。 3. 在Go语言程序中使用protobuf ```go package main import ( "fmt" "example" "github.com/golang/protobuf/proto" ) func main() { p := &example.Person{ Name: "Alice", Age: 20, Hobbies: []string{"swimming", "reading"}, } data, err := proto.Marshal(p) if err != nil { fmt.Println("marshal error:", err) return } p2 := &example.Person{} err = proto.Unmarshal(data, p2) if err != nil { fmt.Println("unmarshal error:", err) return } fmt.Println("p2:", p2) } ``` 该程序使用protobuf将一个Person对象编码为二进制数据,然后解码成另一个Person对象。注意,该程序需要引入github.com/golang/protobuf/proto包,该包提供了protobuf的Go语言支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值