Add wrapper implementation
This commit is contained in:
@@ -12,6 +12,7 @@ type options struct {
|
||||
broker broker.Broker
|
||||
registry registry.Registry
|
||||
transport transport.Transport
|
||||
wrappers []Wrapper
|
||||
}
|
||||
|
||||
// Broker to be used for pub/sub
|
||||
@@ -48,3 +49,10 @@ func Transport(t transport.Transport) Option {
|
||||
o.transport = t
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a Wrapper to a list of options passed into the client
|
||||
func Wrap(w Wrapper) Option {
|
||||
return func(o *options) {
|
||||
o.wrappers = append(o.wrappers, w)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ type rpcClient struct {
|
||||
}
|
||||
|
||||
func newRpcClient(opt ...Option) Client {
|
||||
var once sync.Once
|
||||
|
||||
opts := options{
|
||||
codecs: make(map[string]CodecFunc),
|
||||
}
|
||||
@@ -43,12 +45,19 @@ func newRpcClient(opt ...Option) Client {
|
||||
opts.broker = broker.DefaultBroker
|
||||
}
|
||||
|
||||
var once sync.Once
|
||||
|
||||
return &rpcClient{
|
||||
rc := &rpcClient{
|
||||
once: once,
|
||||
opts: opts,
|
||||
}
|
||||
|
||||
c := Client(rc)
|
||||
|
||||
// wrap in reverse
|
||||
for i := len(opts.wrappers); i > 0; i-- {
|
||||
c = opts.wrappers[i-1](c)
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (r *rpcClient) codecFunc(contentType string) (codecFunc, error) {
|
||||
|
||||
37
client/wrapper.go
Normal file
37
client/wrapper.go
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
Wrapper is a type of middleware for the go-micro client. It allows
|
||||
the client to be "wrapped" so that requests and responses can be intercepted
|
||||
to perform extra requirements such as auth, tracing, monitoring, logging, etc.
|
||||
|
||||
Example usage:
|
||||
|
||||
import (
|
||||
"log"
|
||||
"github.com/micro/go-micro/client"
|
||||
|
||||
)
|
||||
|
||||
type LogWrapper struct {
|
||||
client.Client
|
||||
}
|
||||
|
||||
func (l *LogWrapper) Call(ctx context.Context, req Request, rsp interface{}) error {
|
||||
log.Println("Making request to service " + req.Service() + " method " + req.Method())
|
||||
return w.Client.Call(ctx, req, rsp)
|
||||
}
|
||||
|
||||
func Wrapper(c client.Client) client.Client {
|
||||
return &LogWrapper{c}
|
||||
}
|
||||
|
||||
func main() {
|
||||
c := client.NewClient(client.Wrap(Wrapper))
|
||||
|
||||
}
|
||||
|
||||
|
||||
*/
|
||||
package client
|
||||
|
||||
// Wrapper wraps a client and returns a client
|
||||
type Wrapper func(Client) Client
|
||||
Reference in New Issue
Block a user