2020-07-16 18:32:37 +03:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
2020-08-17 22:44:45 +01:00
|
|
|
"context"
|
2020-08-17 23:09:24 +01:00
|
|
|
"sort"
|
2020-07-16 18:32:37 +03:00
|
|
|
|
2023-04-11 22:20:37 +03:00
|
|
|
"go.unistack.org/micro/v4/errors"
|
|
|
|
"go.unistack.org/micro/v4/router"
|
2020-07-16 18:32:37 +03:00
|
|
|
)
|
|
|
|
|
2020-08-17 22:44:45 +01:00
|
|
|
// LookupFunc is used to lookup routes for a service
|
|
|
|
type LookupFunc func(context.Context, Request, CallOptions) ([]string, error)
|
|
|
|
|
2020-07-16 18:32:37 +03:00
|
|
|
// LookupRoute for a request using the router and then choose one using the selector
|
2021-12-16 15:03:42 +03:00
|
|
|
func LookupRoute(_ context.Context, req Request, opts CallOptions) ([]string, error) {
|
2020-07-30 15:22:36 +01:00
|
|
|
// check to see if an address was provided as a call option
|
|
|
|
if len(opts.Address) > 0 {
|
2020-08-17 22:44:45 +01:00
|
|
|
return opts.Address, nil
|
2020-07-16 18:32:37 +03:00
|
|
|
}
|
|
|
|
|
2020-12-04 02:28:45 +03:00
|
|
|
if opts.Router == nil {
|
|
|
|
return nil, router.ErrRouteNotFound
|
|
|
|
}
|
|
|
|
|
2020-07-16 18:32:37 +03:00
|
|
|
// construct the router query
|
|
|
|
query := []router.QueryOption{router.QueryService(req.Service())}
|
|
|
|
|
|
|
|
// if a custom network was requested, pass this to the router. By default the router will use it's
|
|
|
|
// own network, which is set during initialisation.
|
|
|
|
if len(opts.Network) > 0 {
|
|
|
|
query = append(query, router.QueryNetwork(opts.Network))
|
|
|
|
}
|
|
|
|
|
|
|
|
// lookup the routes which can be used to execute the request
|
|
|
|
routes, err := opts.Router.Lookup(query...)
|
|
|
|
if err == router.ErrRouteNotFound {
|
|
|
|
return nil, errors.InternalServerError("go.micro.client", "service %s: %s", req.Service(), err.Error())
|
|
|
|
} else if err != nil {
|
|
|
|
return nil, errors.InternalServerError("go.micro.client", "error getting next %s node: %s", req.Service(), err.Error())
|
|
|
|
}
|
|
|
|
|
2020-08-17 23:09:24 +01:00
|
|
|
// sort by lowest metric first
|
|
|
|
sort.Slice(routes, func(i, j int) bool {
|
|
|
|
return routes[i].Metric < routes[j].Metric
|
|
|
|
})
|
|
|
|
|
2020-08-21 14:53:21 +03:00
|
|
|
addrs := make([]string, 0, len(routes))
|
2020-08-17 22:44:45 +01:00
|
|
|
for _, route := range routes {
|
|
|
|
addrs = append(addrs, route.Address)
|
2020-07-16 18:32:37 +03:00
|
|
|
}
|
2020-08-17 22:44:45 +01:00
|
|
|
|
|
|
|
return addrs, nil
|
2020-07-16 18:32:37 +03:00
|
|
|
}
|