github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/client/lookup.go (about) 1 // Copyright 2020 Asim Aslam 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // Original source: github.com/micro/go-micro/v3/client/lookup.go 16 17 package client 18 19 import ( 20 "context" 21 "sort" 22 23 "github.com/tickoalcantara12/micro/v3/service/errors" 24 "github.com/tickoalcantara12/micro/v3/service/router" 25 ) 26 27 // LookupFunc is used to lookup routes for a service 28 type LookupFunc func(context.Context, Request, CallOptions) ([]string, error) 29 30 // LookupRoute for a request using the router and then choose one using the selector 31 func LookupRoute(ctx context.Context, req Request, opts CallOptions) ([]string, error) { 32 // check to see if an address was provided as a call option 33 if len(opts.Address) > 0 { 34 return opts.Address, nil 35 } 36 37 // construct the router query 38 query := []router.LookupOption{} 39 40 // if a custom network was requested, pass this to the router. By default the router will use it's 41 // own network, which is set during initialisation. 42 if len(opts.Network) > 0 { 43 query = append(query, router.LookupNetwork(opts.Network)) 44 } 45 46 // lookup the routes which can be used to execute the request 47 routes, err := opts.Router.Lookup(req.Service(), query...) 48 if err == router.ErrRouteNotFound { 49 return nil, errors.InternalServerError("go.micro.client", "service %s: %s", req.Service(), err.Error()) 50 } else if err != nil { 51 return nil, errors.InternalServerError("go.micro.client", "error getting next %s node: %s", req.Service(), err.Error()) 52 } 53 54 // sort by lowest metric first 55 sort.Slice(routes, func(i, j int) bool { 56 return routes[i].Metric < routes[j].Metric 57 }) 58 59 var addrs []string 60 61 for _, route := range routes { 62 addrs = append(addrs, route.Address) 63 } 64 65 return addrs, nil 66 }