Wrappers

Wrappers are middleware for Go Micro

Overview

Wrappers are middleware for Go Micro. We want to create an extensible framework that includes hooks to add extra functionality that’s not a core requirement. A lot of the time you need to execute something like auth, tracing, etc so this provides the ability to do that.

We use the “decorator pattern” for this.

Usage

Here’s some example usage and real code in examples/wrapper.

You can find a range of wrappers in go-plugins/wrapper.

Handler

Here’s an example service handler wrapper which logs the incoming request

  1. // implements the server.HandlerWrapper
  2. func logWrapper(fn server.HandlerFunc) server.HandlerFunc {
  3. return func(ctx context.Context, req server.Request, rsp interface{}) error {
  4. fmt.Printf("[%v] server request: %s", time.Now(), req.Endpoint())
  5. return fn(ctx, req, rsp)
  6. }
  7. }

It can be initialised when creating the service

  1. service := micro.NewService(
  2. micro.Name("greeter"),
  3. // wrap the handler
  4. micro.WrapHandler(logWrapper),
  5. )

Client

Here’s an example of a client wrapper which logs requests made

  1. type logWrapper struct {
  2. client.Client
  3. }
  4. func (l *logWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
  5. fmt.Printf("[wrapper] client request to service: %s endpoint: %s\n", req.Service(), req.Endpoint())
  6. return l.Client.Call(ctx, req, rsp)
  7. }
  8. // implements client.Wrapper as logWrapper
  9. func logWrap(c client.Client) client.Client {
  10. return &logWrapper{c}
  11. }

It can be initialised when creating the service

  1. service := micro.NewService(
  2. micro.Name("greeter"),
  3. // wrap the client
  4. micro.WrapClient(logWrap),
  5. )