2019-07-17 23:19:18 +03:00
|
|
|
package version
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sort"
|
|
|
|
|
2020-01-31 01:26:39 +03:00
|
|
|
"github.com/micro/go-micro/v2/client"
|
|
|
|
"github.com/micro/go-micro/v2/client/selector"
|
|
|
|
"github.com/micro/go-micro/v2/registry"
|
2019-07-17 23:19:18 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// NewClientWrapper is a wrapper which selects only latest versions of services
|
|
|
|
func NewClientWrapper() client.Wrapper {
|
|
|
|
return func(c client.Client) client.Client {
|
|
|
|
return &latestVersionWrapper{
|
|
|
|
Client: c,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type latestVersionWrapper struct {
|
|
|
|
client.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *latestVersionWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
|
|
|
|
nOpts := append(opts, client.WithSelectOption(selector.WithFilter(filterLatestVersion())))
|
|
|
|
return w.Client.Call(ctx, req, rsp, nOpts...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func filterLatestVersion() selector.Filter {
|
|
|
|
return func(svcsOld []*registry.Service) []*registry.Service {
|
2020-04-20 02:47:52 +03:00
|
|
|
|
|
|
|
if len(svcsOld) <= 1 {
|
|
|
|
return svcsOld
|
|
|
|
}
|
|
|
|
|
2019-07-17 23:19:18 +03:00
|
|
|
var svcsNew []*registry.Service
|
|
|
|
versions := make([]string, len(svcsOld))
|
|
|
|
|
|
|
|
for i, svc := range svcsOld {
|
|
|
|
versions[i] = svc.Version
|
|
|
|
}
|
|
|
|
|
|
|
|
sort.Strings(versions)
|
|
|
|
|
|
|
|
gtVersion := versions[len(versions)-1]
|
|
|
|
|
|
|
|
for _, svc := range svcsOld {
|
|
|
|
if svc.Version == gtVersion {
|
|
|
|
svcsNew = append(svcsNew, svc)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return svcsNew
|
|
|
|
}
|
|
|
|
}
|