mirror of
https://github.com/go-micro/go-micro.git
synced 2024-12-18 08:26:38 +02:00
58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
package grpc
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
// ServiceMethod converts a gRPC method to a Go method
|
|
// Input:
|
|
// Foo.Bar, /Foo/Bar, /package.Foo/Bar, /a.package.Foo/Bar
|
|
// Output:
|
|
// [Foo, Bar]
|
|
func ServiceMethod(m string) (string, string, error) {
|
|
if len(m) == 0 {
|
|
return "", "", fmt.Errorf("malformed method name: %q", m)
|
|
}
|
|
|
|
// grpc method
|
|
if m[0] == '/' {
|
|
// [ , Foo, Bar]
|
|
// [ , package.Foo, Bar]
|
|
// [ , a.package.Foo, Bar]
|
|
parts := strings.Split(m, "/")
|
|
if len(parts) != 3 || len(parts[1]) == 0 || len(parts[2]) == 0 {
|
|
return "", "", fmt.Errorf("malformed method name: %q", m)
|
|
}
|
|
service := strings.Split(parts[1], ".")
|
|
return service[len(service)-1], parts[2], nil
|
|
}
|
|
|
|
// non grpc method
|
|
parts := strings.Split(m, ".")
|
|
|
|
// expect [Foo, Bar]
|
|
if len(parts) != 2 {
|
|
return "", "", fmt.Errorf("malformed method name: %q", m)
|
|
}
|
|
|
|
return parts[0], parts[1], nil
|
|
}
|
|
|
|
// ServiceFromMethod returns the service
|
|
// /service.Foo/Bar => service
|
|
func ServiceFromMethod(m string) string {
|
|
if len(m) == 0 {
|
|
return m
|
|
}
|
|
if m[0] != '/' {
|
|
return m
|
|
}
|
|
parts := strings.Split(m, "/")
|
|
if len(parts) < 3 {
|
|
return m
|
|
}
|
|
parts = strings.Split(parts[1], ".")
|
|
return strings.Join(parts[:len(parts)-1], ".")
|
|
}
|