github.com/annwntech/go-micro/v2@v2.9.5/util/grpc/grpc.go (about)

     1  package grpc
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // ServiceMethod converts a gRPC method to a Go method
     9  // Input:
    10  // Foo.Bar, /Foo/Bar, /package.Foo/Bar, /a.package.Foo/Bar
    11  // Output:
    12  // [Foo, Bar]
    13  func ServiceMethod(m string) (string, string, error) {
    14  	if len(m) == 0 {
    15  		return "", "", fmt.Errorf("malformed method name: %q", m)
    16  	}
    17  
    18  	// grpc method
    19  	if m[0] == '/' {
    20  		// [ , Foo, Bar]
    21  		// [ , package.Foo, Bar]
    22  		// [ , a.package.Foo, Bar]
    23  		parts := strings.Split(m, "/")
    24  		if len(parts) != 3 || len(parts[1]) == 0 || len(parts[2]) == 0 {
    25  			return "", "", fmt.Errorf("malformed method name: %q", m)
    26  		}
    27  		service := strings.Split(parts[1], ".")
    28  		return service[len(service)-1], parts[2], nil
    29  	}
    30  
    31  	// non grpc method
    32  	parts := strings.Split(m, ".")
    33  
    34  	// expect [Foo, Bar]
    35  	if len(parts) != 2 {
    36  		return "", "", fmt.Errorf("malformed method name: %q", m)
    37  	}
    38  
    39  	return parts[0], parts[1], nil
    40  }
    41  
    42  // ServiceFromMethod returns the service
    43  // /service.Foo/Bar => service
    44  func ServiceFromMethod(m string) string {
    45  	if len(m) == 0 {
    46  		return m
    47  	}
    48  	if m[0] != '/' {
    49  		return m
    50  	}
    51  	parts := strings.Split(m, "/")
    52  	if len(parts) < 3 {
    53  		return m
    54  	}
    55  	parts = strings.Split(parts[1], ".")
    56  	return strings.Join(parts[:len(parts)-1], ".")
    57  }