github.com/ovsinc/prototool@v1.3.0/internal/grpc/invocation_event_handler.go (about) 1 // Copyright (c) 2018 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package grpc 22 23 import ( 24 "io" 25 26 "github.com/fullstorydev/grpcurl" 27 "github.com/golang/protobuf/jsonpb" 28 "github.com/golang/protobuf/proto" 29 "github.com/jhump/protoreflect/desc" 30 "go.uber.org/zap" 31 "google.golang.org/grpc/metadata" 32 "google.golang.org/grpc/status" 33 ) 34 35 var jsonpbMarshaler = &jsonpb.Marshaler{Indent: " "} 36 37 var _ grpcurl.InvocationEventHandler = &invocationEventHandler{} 38 39 type invocationEventHandler struct { 40 output io.Writer 41 logger *zap.Logger 42 err error 43 } 44 45 func newInvocationEventHandler(output io.Writer, logger *zap.Logger) *invocationEventHandler { 46 return &invocationEventHandler{ 47 output: output, 48 logger: logger, 49 } 50 } 51 52 func (i *invocationEventHandler) OnResolveMethod(*desc.MethodDescriptor) {} 53 54 func (i *invocationEventHandler) OnSendHeaders(metadata.MD) {} 55 56 func (i *invocationEventHandler) OnReceiveHeaders(metadata.MD) {} 57 58 func (i *invocationEventHandler) OnReceiveResponse(message proto.Message) { 59 i.println(i.marshal(message)) 60 } 61 62 func (i *invocationEventHandler) OnReceiveTrailers(s *status.Status, _ metadata.MD) { 63 if err := s.Err(); err != nil { 64 i.err = err 65 } 66 } 67 68 func (i *invocationEventHandler) Err() error { 69 return i.err 70 } 71 72 func (i *invocationEventHandler) marshal(message proto.Message) string { 73 s, err := jsonpbMarshaler.MarshalToString(message) 74 if err != nil { 75 i.logger.Error("marshal error", zap.Error(err)) 76 return "" 77 } 78 return s 79 } 80 81 func (i *invocationEventHandler) println(s string) { 82 if s == "" { 83 return 84 } 85 if _, err := i.output.Write([]byte(s + "\n")); err != nil { 86 i.logger.Error("write error", zap.Error(err)) 87 } 88 }