Skip to content

Latest commit

 

History

History
114 lines (83 loc) · 1.95 KB

7.grpc-gateway.md

File metadata and controls

114 lines (83 loc) · 1.95 KB

Grpc Gateway

https://github.com/grpc-ecosystem/grpc-gateway

什么是 grpc gateway

用http服务代理grpc服务

依赖

// 非项目目录
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

替代品(据说更好用)

https://github.com/vaporz/turbo

代码

grpc-gateway
├── proto
│   ├── build.sh
│   ├── greeter.pb.go
│   ├── greeter.pb.gw.go 注意查看build.sh的变化
│   └── greeter.proto
└── server
    └── main.go

grpc-gateway/proto/greeter.proto

syntax = "proto3";

package greeter;

import "google/api/annotations.proto";

service Greeter {
    rpc Hello(Request) returns (Response) {
        option (google.api.http) = {
			post: "/greeter/hello"
			body: "*"
		};
    }
}

message Request {
    string name = 1;
}

message Response {
    string msg = 1;
}

grpc-gateway/server/main.go

package server

import (
	"flag"
	"net/http"

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

	 "github.com/cheerego/go-micro-in-action/grpc-gateway/proto"
)

var (
	// the go.micro.srv.greeter address 在启动的时候可以看到
	endpoint = flag.String("endpoint", "localhost:58863", "go.micro.srv.greeter address")
)

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

	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}

	err := greeter.RegisterGreeterHandlerFromEndpoint(ctx, mux, *endpoint, opts)
	if err != nil {
		return err
	}

	return http.ListenAndServe(":9090", mux)
}

func main() {
	flag.Parse()

	defer glog.Flush()

	if err := run(); err != nil {
		glog.Fatal(err)
	}
}

Api访问

curl -H 'Content-Type: application/json' -d '{"name": "Asim"}' http://127.0.0.1:9090/greeter/hello