demo grpc+http

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)
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值