protoc生成go代码
#protoc -I [目标路径] [目标文件] --go_out=plugins=grpc:[编译至路径]
protoc -I ./ ./user.proto --go_out=plugins=grpc:.
#生成的go代码以 文件名.pb.go命名 如上面命令生成的就是user.pb.go
protoc -I/usr/local/include -I. -I$GOPATH/src -Igoogleapis/ --go_out=plugins=grpc:. user.proto
demo grpc+http
https://cloud.tencent.com/developer/article/1435754
gateway
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
go get -u github.com/golang/protobuf/protoc-gen-go
protoc -I. -Igoogleapis/ ./test.proto --go_out=plugins=grpc:.
protoc --proto_path=../ -I/usr/local/include -I. -I$GOPATH/src -Igoogleapis --grpc-gateway_out=logtostderr=true:. test.proto
//gateway.proto
syntax = "proto3";
package gateway;
// 新增以下引入
import "google/api/annotations.proto";
message StringMessage {
string value = 1;
}
// # 修改方法增加http定义
// # service Gateway {
// # rpc SayHello Echo(StringMessage) returns (StringMessage) {}
// # }
service Gateway {
rpc Echo(StringMessage) returns (StringMessage) {
option (google.api.http) = {
post: "/v1/example/echo"
body: "*"
};
}
}
//service
package main
import (
"log"
"net"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "grpc_gateway_demo/proto"
)
const (
PORT = ":9192"
)
type server struct {}
func (s *server) Echo(ctx context.Context, in *pb.StringMessage) (*pb.StringMessage, error) {
log.Println("request: ", in.Value)
return &pb.StringMessage{Value: "Hello " + in.Value}, nil
}
func main() {
lis, err := net.Listen("tcp", PORT)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGatewayServer(s, &server{})
log.Println("rpc服务已经开启")
s.Serve(lis)
}
//gateway 端接收http请求
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"golang.org/x/net/context"
"google.golang.org/grpc"
gw "grpc_gateway_demo/proto"
)
var (
echoEndpoint = flag.String("test_endpoint", "localhost:9192", "endpoint of service")
//只有中间的ip:端口有用
//
)
func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
fmt.Println(*echoEndpoint)
err := gw.RegisterGatewayHandlerFromEndpoint(ctx, mux, *echoEndpoint, opts)
if err != nil {
return err
}
log.Println("服务开启")
return http.ListenAndServe(":8080", mux)
}
func main() {
flag.Parse()
defer glog.Flush()
if err := run(); err != nil {
glog.Fatal(err)
}
}