用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
grpc-gateway
├── proto
│ ├── build.sh
│ ├── greeter.pb.go
│ ├── greeter.pb.gw.go 注意查看build.sh的变化
│ └── greeter.proto
└── server
└── main.go
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;
}
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)
}
}
curl -H 'Content-Type: application/json' -d '{"name": "Asim"}' http://127.0.0.1:9090/greeter/hello