-
Notifications
You must be signed in to change notification settings - Fork 2
/
application.go
83 lines (67 loc) · 2.2 KB
/
application.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package grpc
import (
"context"
"errors"
"fmt"
"net"
"github.com/oarkflow/framework/facades"
grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type Application struct {
server *grpc.Server
unaryClientInterceptorGroups map[string][]grpc.UnaryClientInterceptor
}
func NewApplication() *Application {
return &Application{}
}
func (app *Application) Server() *grpc.Server {
return app.server
}
func (app *Application) Client(ctx context.Context, name string) (*grpc.ClientConn, error) {
host := facades.Config.GetString(fmt.Sprintf("grpc.clients.%s.host", name))
if host == "" {
return nil, errors.New("client is not defined")
}
interceptors, ok := facades.Config.Get(fmt.Sprintf("grpc.clients.%s.interceptors", name)).([]string)
if !ok {
return nil, fmt.Errorf("the type of clients.%s.interceptors must be []string", name)
}
clientInterceptors := app.getClientInterceptors(interceptors)
return grpc.DialContext(
ctx,
host,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithChainUnaryInterceptor(clientInterceptors...),
)
}
func (app *Application) Run(host string) error {
listen, err := net.Listen("tcp", host)
if err != nil {
return err
}
if err := app.server.Serve(listen); err != nil {
return err
}
return nil
}
func (app *Application) UnaryServerInterceptors(unaryServerInterceptors []grpc.UnaryServerInterceptor) {
app.server = grpc.NewServer(grpc.UnaryInterceptor(
grpcmiddleware.ChainUnaryServer(unaryServerInterceptors...),
))
}
func (app *Application) UnaryClientInterceptorGroups(unaryClientInterceptorGroups map[string][]grpc.UnaryClientInterceptor) {
app.unaryClientInterceptorGroups = unaryClientInterceptorGroups
}
func (app *Application) getClientInterceptors(interceptors []string) []grpc.UnaryClientInterceptor {
var unaryClientInterceptors []grpc.UnaryClientInterceptor
for _, interceptor := range interceptors {
for client, clientInterceptors := range app.unaryClientInterceptorGroups {
if interceptor == client {
unaryClientInterceptors = append(unaryClientInterceptors, clientInterceptors...)
}
}
}
return unaryClientInterceptors
}