網(wǎng)站舉報(bào)網(wǎng)怎樣申請(qǐng)自己的電商平臺(tái)
option自定義http規(guī)則和http body響應(yīng)
簡(jiǎn)介
本篇接上文
golang 工程組件:grpc-gateway 環(huán)境安裝+默認(rèn)網(wǎng)關(guān)測(cè)試
默認(rèn)網(wǎng)關(guān)配置終究是難用,本篇介紹一下proto里采用option自定義http規(guī)則以及讓網(wǎng)關(guān)返回http
響應(yīng)而不是我們定義的grpc
響應(yīng)
option定義http規(guī)則和httpbody響應(yīng)
引入庫(kù)。可以直接拷貝grpc-gateway源碼下google文件夾到項(xiàng)目下
import "google/api/annotations.proto";
import "google/api/httpbody.proto";
import "google/protobuf/empty.proto";
user.proto
syntax = "proto3";
package echo;
option go_package = "echo/proto";import "google/api/annotations.proto";
import "google/api/httpbody.proto";
import "google/protobuf/empty.proto";message User{int64 id = 1;// 改成下劃線形式string userName = 2[json_name="user_name"];int32 age = 3;string phone = 4;Addr addr = 5;
}message Addr {string province = 1;string city = 2;string county = 3;
}service Echo{rpc Get(User) returns (User) {//get請(qǐng)求option (google.api.http) = {get: "/echo/user/{id}"};}rpc AddOrUpdate(User) returns (User) {option (google.api.http) = {post: "/echo/user"// * 表示接受user所有字段body: "*"additional_bindings {put: "/echo/user"body: "*"}//patch 請(qǐng)求,只更新部分字段additional_bindings {patch: "/echo/user"body: "addr"}};}rpc Delete(User) returns (User) {option (google.api.http) = {delete: "/echo/user/{id}"};}// httpbody響應(yīng),前面是grpc定義的消息rpc List(google.protobuf.Empty) returns (stream google.api.HttpBody) {option (google.api.http) = {get: "/echo/user/list"};}
}
對(duì)應(yīng)grpc實(shí)現(xiàn)
server.go
package serverimport ("context""echo/proto""fmt""github.com/golang/protobuf/jsonpb"_ "github.com/golang/protobuf/jsonpb""google.golang.org/genproto/googleapis/api/httpbody"_ "google.golang.org/genproto/googleapis/api/httpbody""google.golang.org/protobuf/types/known/emptypb"_ "google.golang.org/protobuf/types/known/emptypb"
)type echoServer struct {proto.UnimplementedEchoServer
}func NewServer() proto.EchoServer {return &echoServer{}
}
func (s *echoServer) Get(ctx context.Context, in *proto.User) (*proto.User, error) {fmt.Printf("%+v\n", in)return in, nil
}
func (s *echoServer) AddOrUpdate(ctx context.Context, in *proto.User) (*proto.User, error) {fmt.Printf("%+v\n", in)return in, nil
}
func (s *echoServer) Delete(ctx context.Context, in *proto.User) (*proto.User, error) {fmt.Printf("%+v\n", in)return in, nil
}func (s *echoServer) List(in *emptypb.Empty, stream proto.Echo_ListServer) error {userList := []*proto.User{{Id: 1,UserName: "test1",Addr: &proto.Addr{Province: "深圳1",},},{Id: 2,UserName: "test2",Addr: &proto.Addr{Province: "深圳2",},},{Id: 3,UserName: "test3",Addr: &proto.Addr{Province: "深圳3",},},}for _, u := range userList {//jsonpb庫(kù)序列化返回的才是下劃線形式。 json序列化不讀tag里定義m := jsonpb.Marshaler{}data, _ := m.MarshalToString(u)msg := &httpbody.HttpBody{ContentType: "application/json",Data: []byte(data),}stream.Send(msg)}return nil
}
啟動(dòng)后按對(duì)應(yīng)路由訪問(wèn)即可。 網(wǎng)關(guān)和啟動(dòng)源碼在上文里