github.phpd.cn/hashicorp/consul@v1.4.5/agent/consul/state/index_connect.go (about)

     1  package state
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/hashicorp/consul/agent/structs"
     8  )
     9  
    10  // IndexConnectService indexes a *struct.ServiceNode for querying by
    11  // services that support Connect to some target service. This will
    12  // properly index the proxy destination for proxies and the service name
    13  // for native services.
    14  type IndexConnectService struct{}
    15  
    16  func (idx *IndexConnectService) FromObject(obj interface{}) (bool, []byte, error) {
    17  	sn, ok := obj.(*structs.ServiceNode)
    18  	if !ok {
    19  		return false, nil, fmt.Errorf("Object must be ServiceNode, got %T", obj)
    20  	}
    21  
    22  	var result []byte
    23  	switch {
    24  	case sn.ServiceKind == structs.ServiceKindConnectProxy:
    25  		// For proxies, this service supports Connect for the destination
    26  		result = []byte(strings.ToLower(sn.ServiceProxy.DestinationServiceName))
    27  
    28  	case sn.ServiceConnect.Native:
    29  		// For native, this service supports Connect directly
    30  		result = []byte(strings.ToLower(sn.ServiceName))
    31  
    32  	default:
    33  		// Doesn't support Connect at all
    34  		return false, nil, nil
    35  	}
    36  
    37  	// Return the result with the null terminator appended so we can
    38  	// differentiate prefix vs. non-prefix matches.
    39  	return true, append(result, '\x00'), nil
    40  }
    41  
    42  func (idx *IndexConnectService) FromArgs(args ...interface{}) ([]byte, error) {
    43  	if len(args) != 1 {
    44  		return nil, fmt.Errorf("must provide only a single argument")
    45  	}
    46  
    47  	arg, ok := args[0].(string)
    48  	if !ok {
    49  		return nil, fmt.Errorf("argument must be a string: %#v", args[0])
    50  	}
    51  
    52  	// Add the null character as a terminator
    53  	return append([]byte(strings.ToLower(arg)), '\x00'), nil
    54  }