grpc,rpc,protobuf,RestAPI
high-performance, opensource univiesal RPC framework
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/golang/protobuf/protoc-gen-go
(optional) go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
~/github.com/rpcRestService/message/myservice.proto
syntax = "proto3";
package example;
import "google/api/annotations.proto";
message StringMessage {
string value = 1;
}
service MyService {
rpc Echo(StringMessage) returns (StringMessage) {
option (google.api.http) = {
post: "/v1/example/echo"
body: "*"
};
}
}
StringMessage 는 struct와 같은 개념을 가지고 안에 value가 멤버면수(?)와 같은 형태로 존재하게 ehlsek.
<figure class="highlight"><pre><code class="language-shell" data-lang="shell">protoc <span class="nt">-I</span>/usr/local/include <span class="nt">-I</span><span class="nb">.</span> <span class="se">\</span>
<span class="nt">-I</span><span class="nv">$GOPATH</span>/src <span class="se">\</span>
<span class="nt">-I</span><span class="nv">$GOPATH</span>/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis <span class="se">\</span>
<span class="nt">--go_out</span><span class="o">=</span><span class="nv">plugins</span><span class="o">=</span>grpc:. <span class="se">\</span>
myservice.proto
</code></pre></figure>
github.com/rpcRestService/server/gServer.go
package main
import (
"fmt"
pb "github.com/rpcRestService/message"
"golang.org/x/net/context"
"google.golang.org/grpc"
"log"
"net"
)
type server struct{}
func (s *server) Echo(ctx context.Context, in *pb.StringMessage) (*pb.StringMessage, error) {
strmsg := &pb.StringMessage{Value: in.Value}
return strmsg, nil
}
func main() {
lis, err := net.Listen("tcp", ":5505")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterMyServiceServer(s, &server{})
s.Serve(lis)
}
protoc -I/usr/local/include -I. \
-I$GOPATH/src \
-I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
--grpc-gateway_out=logtostderr=true:. \
myservice.proto
github.com/rpcRestService/server/main.go
package main
import (
"flag"
"github.com/golang/glog"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
gw "github.com/rpcRestService/message"
"golang.org/x/net/context"
"google.golang.org/grpc"
"net/http"
)
func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
err := gw.RegisterMyServiceHandlerFromEndpoint(ctx, mux, "localhost:1234", opts)
if err != nil {
return err
}
return http.ListenAndServe(":8080", mux)
}
func main() {
flag.Parse()
defer glog.Flush()
if err := run(); err != nil {
glog.Fatal(err)
}
}
curl -X POST -k localhost:8080/v1/example/echo -d '{"value":"this is vlaue"}'
{"value":"this is vlaue"}
서버딴에 모듈들이 어떻게 통신하며 의사소통하는지 궁금했는데 하나의 방법을 찾은듯하다.
키워드를 얻어 공부했지만.. 실제로 얼마나 좋은(?) 편리한 것인지 알게되면 .. 추가적으로 작성해보도록 하겠다!
##