forked from ktr0731/evans
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
50 lines (42 loc) · 1.09 KB
/
grpc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package gateway
import (
"context"
"errors"
"fmt"
"strings"
"google.golang.org/grpc"
"github.com/ktr0731/evans/config"
)
type GRPCClient struct {
config *config.Config
conn *grpc.ClientConn
}
func NewGRPCClient(config *config.Config) (*GRPCClient, error) {
// TODO: secure option
conn, err := grpc.Dial(fmt.Sprintf("%s:%s", config.Server.Host, config.Server.Port), grpc.WithInsecure())
if err != nil {
return nil, err
}
return &GRPCClient{
config: config,
conn: conn,
}, nil
}
func (c *GRPCClient) Invoke(ctx context.Context, fqrn string, req, res interface{}) error {
endpoint, err := c.fqrnToEndpoint(fqrn)
if err != nil {
return err
}
return grpc.Invoke(ctx, endpoint, req, res, c.conn)
}
// fqrnToEndpoint converts FullQualifiedRPCName to endpoint
//
// e.g.
// pkg_name.svc_name.rpc_name -> /pkg_name.svc_name/rpc_name
func (c *GRPCClient) fqrnToEndpoint(fqrn string) (string, error) {
sp := strings.Split(fqrn, ".")
if len(sp) < 3 {
return "", errors.New("invalid FQRN format")
}
return fmt.Sprintf("/%s/%s", strings.Join(sp[:len(sp)-1], "."), sp[len(sp)-1]), nil
}