-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserve.go
58 lines (52 loc) · 1.34 KB
/
serve.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
51
52
53
54
55
56
57
58
package mfscsi
import (
"context"
"fmt"
"net"
"os"
"strings"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
type Registrar interface {
Register(*grpc.Server)
}
func Serve(ctx context.Context, endpoint string, services ...Registrar) error {
var proto, addr string
if strings.HasPrefix(strings.ToLower(endpoint), "unix://") ||
strings.HasPrefix(strings.ToLower(endpoint), "tcp://") {
s := strings.SplitN(endpoint, "://", 2)
if s[1] != "" {
proto, addr = s[0], s[1]
}
}
if proto == "" || addr == "" {
return fmt.Errorf("Invalid endpoint: %v", endpoint)
}
if proto == "unix" {
addr = "/" + addr
if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
return err
}
}
listener, err := net.Listen(proto, addr)
if err != nil {
return err
}
server := grpc.NewServer(grpc.ChainUnaryInterceptor(logCmd))
for _, svc := range services {
svc.Register(server)
}
go func() {
<-ctx.Done()
server.GracefulStop()
}()
return server.Serve(listener)
}
func logCmd(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
resp, err = handler(ctx, req)
logrus.New().WithField("mthd", info.FullMethod).WithField("err", err).
WithField("req", fmt.Sprintf("%v", req)).WithField("resp", fmt.Sprintf("%v", resp)).
Info("handled")
return resp, err
}