gitee.com/sasukebo/go-micro/v4@v4.7.1/plugins/wrapper/README.md (about) 1 # Wrappers 2 3 Wrappers are a form of middleware that can be used with go-micro services. They can wrap both 4 the Client and Server handlers. 5 6 ## Client Interface 7 8 ```go 9 // Wrapper wraps a client and returns a client 10 type Wrapper func(Client) Client 11 12 // StreamWrapper wraps a Stream and returns the equivalent 13 type StreamWrapper func(Streamer) Streamer 14 ``` 15 16 ## Handler Interface 17 18 ```go 19 // HandlerFunc represents a single method of a handler. It's used primarily 20 // for the wrappers. What's handed to the actual method is the concrete 21 // request and response types. 22 type HandlerFunc func(ctx context.Context, req Request, rsp interface{}) error 23 24 // SubscriberFunc represents a single method of a subscriber. It's used primarily 25 // for the wrappers. What's handed to the actual method is the concrete 26 // publication message. 27 type SubscriberFunc func(ctx context.Context, msg Event) error 28 29 // HandlerWrapper wraps the HandlerFunc and returns the equivalent 30 type HandlerWrapper func(HandlerFunc) HandlerFunc 31 32 // SubscriberWrapper wraps the SubscriberFunc and returns the equivalent 33 type SubscriberWrapper func(SubscriberFunc) SubscriberFunc 34 35 // StreamerWrapper wraps a Streamer interface and returns the equivalent. 36 // Because streams exist for the lifetime of a method invocation this 37 // is a convenient way to wrap a Stream as its in use for trace, monitoring, 38 // metrics, etc. 39 type StreamerWrapper func(Streamer) Streamer 40 ``` 41 42 ## Client Wrapper Usage 43 44 Here's a basic log wrapper for the client 45 46 ```go 47 type logWrapper struct { 48 client.Client 49 } 50 51 func (l *logWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error { 52 md, _ := metadata.FromContext(ctx) 53 fmt.Printf("[Log Wrapper] ctx: %v service: %s method: %s\n", md, req.Service(), req.Endpoint()) 54 return l.Client.Call(ctx, req, rsp) 55 } 56 57 func NewLogWrapper(c client.Client) client.Client { 58 return &logWrapper{c} 59 } 60 ``` 61 62 63 ## Handler Wrapper Usage 64 65 Here's a basic log wrapper for the handler 66 67 ```go 68 func NewLogWrapper(fn server.HandlerFunc) server.HandlerFunc { 69 return func(ctx context.Context, req server.Request, rsp interface{}) error { 70 log.Printf("[Log Wrapper] Before serving request method: %v", req.Endpoint()) 71 err := fn(ctx, req, rsp) 72 log.Printf("[Log Wrapper] After serving request") 73 return err 74 } 75 } 76 ```