-
Notifications
You must be signed in to change notification settings - Fork 2
/
gateway.go
122 lines (106 loc) · 3.15 KB
/
gateway.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package gateway
import (
"context"
"net/http"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/rs/cors"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
var log = logrus.WithField("prefix", "gateway")
// RegistrationFunc defines a gRPC gateway registration func
// which is generated by protoc into a pb.gw.go generated file.
type RegistrationFunc func(
ctx context.Context,
mux *gwruntime.ServeMux,
addr string,
opts []grpc.DialOption,
) error
// Config for the gRPC gateway server.
type Config struct {
RemoteAddress string
GatewayAddress string
AllowedOrigins []string
EndpointsToRegister []RegistrationFunc
}
// Gateway is the gRPC gateway to serve HTTP JSON traffic as a proxy and forward
// it to the gRPC server.
type Gateway struct {
conn *grpc.ClientConn
ctx context.Context
cancel context.CancelFunc
gatewayAddr string
remoteAddr string
server *http.Server
mux *http.ServeMux
allowedOrigins []string
endpointsToRegister []RegistrationFunc
startFailure error
}
// New returns a new gateway server which translates HTTP into gRPC.
// Accepts a context and optional http.ServeMux.
func New(ctx context.Context, cfg *Config) *Gateway {
return &Gateway{
ctx: ctx,
remoteAddr: cfg.RemoteAddress,
gatewayAddr: cfg.GatewayAddress,
mux: http.NewServeMux(),
allowedOrigins: cfg.AllowedOrigins,
endpointsToRegister: cfg.EndpointsToRegister,
}
}
// Start the gateway service. This serves the HTTP JSON traffic.
func (g *Gateway) Start() {
ctx, cancel := context.WithCancel(g.ctx)
g.cancel = cancel
gwmux := gwruntime.NewServeMux(
gwruntime.WithMarshalerOption(
gwruntime.MIMEWildcard, &gwruntime.JSONPb{},
),
)
opts := []grpc.DialOption{grpc.WithInsecure()}
for _, f := range g.endpointsToRegister {
if err := f(ctx, gwmux, g.remoteAddr, opts); err != nil {
log.Fatalf("Could not register API handler with grpc endpoint: %v", err)
}
}
g.mux.Handle("/", g.corsMiddleware(gwmux))
g.server = &http.Server{
Addr: g.gatewayAddr,
Handler: g.mux,
}
go func() {
log.WithField("address", g.gatewayAddr).Info("Starting gRPC gateway")
if err := g.server.ListenAndServe(); err != http.ErrServerClosed {
log.WithError(err).Error("Failed to listen and serve")
g.startFailure = err
}
}()
}
// Status of grpc gateway. Returns an error if this service is unhealthy.
func (g *Gateway) Status() error {
if g.startFailure != nil {
return g.startFailure
}
return nil
}
// Stop the gateway with a graceful shutdown.
func (g *Gateway) Stop() error {
if err := g.server.Shutdown(g.ctx); err != nil {
log.WithError(err).Error("Failed to shut down server")
}
if g.cancel != nil {
g.cancel()
}
return nil
}
func (g *Gateway) corsMiddleware(h http.Handler) http.Handler {
c := cors.New(cors.Options{
AllowedOrigins: g.allowedOrigins,
AllowedMethods: []string{http.MethodPost, http.MethodGet, http.MethodOptions},
AllowCredentials: true,
MaxAge: 600,
AllowedHeaders: []string{"*"},
})
return c.Handler(h)
}