github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/template/api/client/example.go (about)

     1  package client
     2  
     3  import (
     4  	"context"
     5  
     6  	example "github.com/micro/go-micro/examples/template/srv/proto/example"
     7  	"github.com/micro/go-micro/v2"
     8  	"github.com/micro/go-micro/v2/server"
     9  )
    10  
    11  type exampleKey struct{}
    12  
    13  // FromContext retrieves the client from the Context
    14  func ExampleFromContext(ctx context.Context) (example.ExampleService, bool) {
    15  	c, ok := ctx.Value(exampleKey{}).(example.ExampleService)
    16  	return c, ok
    17  }
    18  
    19  // Client returns a wrapper for the ExampleClient
    20  func ExampleWrapper(service micro.Service) server.HandlerWrapper {
    21  	client := example.NewExampleService("go.micro.srv.template", service.Client())
    22  
    23  	return func(fn server.HandlerFunc) server.HandlerFunc {
    24  		return func(ctx context.Context, req server.Request, rsp interface{}) error {
    25  			ctx = context.WithValue(ctx, exampleKey{}, client)
    26  			return fn(ctx, req, rsp)
    27  		}
    28  	}
    29  }