github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/docs/v2/library/go-wrappers.md (about)

     1  ---
     2  title: Wrappers
     3  keywords: go-micro, framework, wrappers
     4  tags: [go-micro, framework, wrappers]
     5  sidebar: home_sidebar
     6  permalink: /go-wrappers
     7  summary: Wrappers are middleware for Go Micro
     8  ---
     9  
    10  # Overview
    11  
    12  Wrappers are middleware for Go Micro. We want to create an extensible framework that includes hooks to add extra 
    13  functionality that's not a core requirement. A lot of the time you need to execute something like auth, tracing, etc 
    14  so this provides the ability to do that.
    15  
    16  We use the "decorator pattern" for this.
    17  
    18  ## Usage
    19  
    20  Here's some example usage and real code in [examples/wrapper](https://github.com/micro/examples/tree/master/wrapper).
    21  
    22  You can find a range of wrappers in [go-plugins/wrapper](https://github.com/micro/go-plugins/tree/master/wrapper).
    23  
    24  ### Handler
    25  
    26  Here's an example service handler wrapper which logs the incoming request
    27  
    28  ```go
    29  // implements the server.HandlerWrapper
    30  func logWrapper(fn server.HandlerFunc) server.HandlerFunc {
    31  	return func(ctx context.Context, req server.Request, rsp interface{}) error {
    32  		fmt.Printf("[%v] server request: %s", time.Now(), req.Endpoint())
    33  		return fn(ctx, req, rsp)
    34  	}
    35  }
    36  ```
    37  
    38  It can be initialised when creating the service
    39  
    40  ```go
    41  service := micro.NewService(
    42  	micro.Name("greeter"),
    43  	// wrap the handler
    44  	micro.WrapHandler(logWrapper),
    45  )
    46  ```
    47  
    48  ### Client
    49  
    50  Here's an example of a client wrapper which logs requests made
    51  
    52  ```go
    53  type logWrapper struct {
    54  	client.Client
    55  }
    56  
    57  func (l *logWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
    58  	fmt.Printf("[wrapper] client request to service: %s endpoint: %s\n", req.Service(), req.Endpoint())
    59  	return l.Client.Call(ctx, req, rsp)
    60  }
    61  
    62  // implements client.Wrapper as logWrapper
    63  func logWrap(c client.Client) client.Client {
    64  	return &logWrapper{c}
    65  }
    66  ```
    67  
    68  It can be initialised when creating the service
    69  
    70  ```go
    71  service := micro.NewService(
    72  	micro.Name("greeter"),
    73  	// wrap the client
    74  	micro.WrapClient(logWrap),
    75  )
    76  ```
    77